André Cytryn André Cytryn - 1 year ago 144
Objective-C Question

Best way to refresh/reload UIScrollView

I have a method that adds some subviews (images/buttons) to my ScrollView.

The thing is that from outside of the ScrollView the user can tap a button that will change the content of the ScrollView.

Is there any decent way to "reset" the ScrollView better than:

for (UIView * view in myScrollView.subViews) {
[view removeFromSuperview];

Note that this solution removes the bar to indicate the position on the ScrollView

lxt lxt
Answer Source

Calling setNeedsDisplay is just going to redraw your scroll view, not actually remove the content inside of it.

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];

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download