刷新/重新加载 UIScrollView 的最佳方法

Best way to refresh/reload UIScrollView(刷新/重新加载 UIScrollView 的最佳方法)

本文介绍了刷新/重新加载 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.

另一种略显老套的方法是在遍历视图时对其进行测试:

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

本文标题为:刷新/重新加载 UIScrollView 的最佳方法