Remove all subviews?
Edit: With thanks to cocoafan: This situation is muddled up by the fact that NSView
and UIView
handle things differently. For NSView
(desktop Mac development only), you can simply use the following:
[someNSView setSubviews:[NSArray array]];
For UIView
(iOS development only), you can safely use makeObjectsPerformSelector:
because the subviews
property will return a copy of the array of subviews:
[[someUIView subviews]
makeObjectsPerformSelector:@selector(removeFromSuperview)];
Thank you to Tommy for pointing out that makeObjectsPerformSelector:
appears to modify the subviews
array while it is being enumerated (which it does for NSView
, but not for UIView
).
Please see this SO question for more details.
Note: Using either of these two methods will remove every view that your main view contains and release them, if they are not retained elsewhere. From Apple's documentation on removeFromSuperview:
If the receiver’s superview is not nil, this method releases the receiver. If you plan to reuse the view, be sure to retain it before calling this method and be sure to release it as appropriate when you are done with it or after adding it to another view hierarchy.
Get all the subviews from your root controller and send each a removeFromSuperview:
NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
In Swift you can use a functional approach like this:
view.subviews.forEach { $0.removeFromSuperview() }
As a comparison, the imperative approach would look like this:
for subview in view.subviews {
subview.removeFromSuperview()
}
These code snippets only work in iOS / tvOS though, things are a little different on macOS.