問題描述
我有一種方法可以將一些子視圖(圖像/按鈕)添加到我的 ScrollView.
I have a method that adds some subviews (images/buttons) to my ScrollView.
問題是,用戶可以從 ScrollView 外部點擊一個按鈕,該按鈕將更改 ScrollView 的內容.
The thing is that from outside of the ScrollView the user can tap a button that will change the content of the ScrollView.
有沒有比重置"ScrollView更好的方法:
Is there any decent way to "reset" the ScrollView better than:
for (UIView * view in myScrollView.subViews) {
[view removeFromSuperview];
}
請注意,此解決方案移除了指示 ScrollView 上位置的欄
Note that this solution removes the bar to indicate the position on the ScrollView
推薦答案
調用 setNeedsDisplay
只是重新繪制滾動視圖,而不是實際刪除其中的內容.
Calling setNeedsDisplay
is just going to redraw your scroll view, not actually remove the content inside of it.
正如您所發現的,在所有滾動視圖子視圖上調用 removeFromSuperview
有時也會導致滾動條也被刪除(不是很好).
As you've discovered, calling removeFromSuperview
on all scroll view subviews will result in your scroll bars sometimes being removed as well (not great).
有幾種方法可以解決這個問題:第一種是維護一個不同的數組,其中包含您自己添加到滾動視圖中的所有視圖.然后,您可以只迭代這個數組.在我看來,這可能是最好的方法.
There are a couple of approaches around this: the first is to maintain a distinct array containing all the views you yourself have added to the scroll view. You can then just iterate through this array instead. In my view this is probably the best approach.
另一種略顯老套的方法是在遍歷視圖時對其進行測試:
The other, slightly hacky, way is to test the views as you iterate through them:
for (UIView *view in self.contentView.subviews)
{
if (![view isKindOfClass:[UIImageView class]])
[view removeFromSuperview];
}
因為滾動條本身是 UIImageView
子類,所以不會刪除它們.但是話又說回來,如果您自己使用圖像視圖,它們也不會被刪除,并且不能保證在未來的 iOS 版本中它們將保持圖像視圖.
Because the scroll bars are themselves a UIImageView
subclass this will not remove them. But then again, if you're using image views yourself they won't get removed either, and there's no guarantee in future iOS versions they will remain image views.
使用我的第一種方法要好得多,只需保留一個包含您添加的所有視圖的數組.
So much better to go with my first approach and just keep an array around with all the views you've added.
這篇關于刷新/重新加載 UIScrollView 的最佳方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!