刷新/重新加载UIScrollView的最佳方法 [英] Best way to refresh/reload UIScrollView

查看:511
本文介绍了刷新/重新加载UIScrollView的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以将一些子视图(图像/按钮)添加到我的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.

另一种,稍微有点hacky的方式是在迭代它们时测试视图:

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的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆