how to remove subviews from scrollview?
I don't think you should use the fast enumeration suggestion.
for(UIView *subview in [view subviews]) {
[subview removeFromSuperview];
}
Isn't this supposed to throw an exception if you change the collection being iterated? http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocFastEnumeration.html#//apple_ref/doc/uid/TP30001163-CH18-SW3
This example may be better.
NSArray *subviews = [[scroller subviews] copy];
for (UIView *subview in subviews) {
[subview removeFromSuperview];
}
[subviews release];
To remove all the subviews from any view, you can iterate over the subviews and send each a removeFromSuperview
call:
// With some valid UIView *view:
for(UIView *subview in [view subviews]) {
[subview removeFromSuperview];
}
This is entirely unconditional, though, and will get rid of all subviews in the given view. If you want something more fine-grained, you could take any of several different approaches:
- Maintain your own arrays of views of different types so you can send them
removeFromSuperview
messages later in the same manner - Retain all your views where you create them and hold on to pointers to those views, so you can send them
removeFromSuperview
individually as necessary - Add an
if
statement to the above loop, checking for class equality. For example, to only remove all the UIButtons (or custom subclasses of UIButton) that exist in a view, you could use something like:
// Again, valid UIView *view:
for(UIView *subview in [view subviews]) {
if([subview isKindOfClass:[UIButton class]]) {
[subview removeFromSuperview];
} else {
// Do nothing - not a UIButton or subclass instance
}
}
To add to what Tim said, I noticed that you are tagging your views. If you wanted to remove a view with a certain tag you could use:
[[myScrollView viewWithTag:myButtonTag] removeFromSuperview];
An old question; but as it's the first hit on Google for this I thought I'd also make a note that there's also this method:
[[myScrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
You can't do the isKindOfClass check with this, but it's still a good solution to know about.
Edit: Another point to note is that the scrollbar of a scrollview is added as a subview to that scrollview. Thus if you iterate through all the subviews of a scrollview you will come across it. If removed it'll add itself again - but it's important to know this if you're only expecting your own UIView subclasses to be in there.
Amendment for Swift 3:
myScrollView.subviews.forEach { $0.removeFromSuperview() }