When my app gets back to its root view controller, in the viewDidAppear:
method I need to remove all subviews.
How can I do this?
Managing Subviews To remove an arranged subview that you no longer want around, you need to call removeFromSuperview() on it. The stack view will automatically remove it from the arranged subview list.
let subViews: Array = self.subviews.copy() for (var subview: NSView!) in subViews { subview.removeFromSuperview() } By doing .copy(), I could perform the removal of each subview while mutating the self.subviews array.
How To Add, Insert, Move, Remove Sub View In iOS Swift 1 Manage Swift View And Subview Example Demo. First let us look at this example in a video as below. ... 2 Manage Swift Subview Functions Introduction. parentViewObject.addSubview ( subView : UIView ) : Add a subview to parent view. ... 3 Manage Swift Subview Example Source Code.
extension UIView { func lf_removeAllSubviews() { for view in self.subviews { view.removeFromSuperview() } } } So that you can use self.view.lf_removeAllSubviews in a UIViewController.
2 @datayeah They are not but there is a big difference between NSView(OS X) and UIView(iOS). – Sulthan Jan 26 '16 at 20:29 @Sulthan you're right. I came here for the Swift answer for UIView and did'nt read your whole code snippet ;) – dy_ Jan 26 '16 at 21:16 1 Swift 4 gives an error: Cannot assign to property: 'subviews' is a get-only property.
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With