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?
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?
Edit: With thanks to cocoafan: This situation is muddled up by the fact that
NSView
andUIView
handle things differently. ForNSView
(desktop Mac development only), you can simply use the following:For
UIView
(iOS development only), you can safely usemakeObjectsPerformSelector:
because thesubviews
property will return a copy of the array of subviews:Thank you to Tommy for pointing out that
makeObjectsPerformSelector:
appears to modify thesubviews
array while it is being enumerated (which it does forNSView
, but not forUIView
).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:
In order to remove all subviews Syntax :
Usage :
This method is present in NSArray.h file and uses NSArray(NSExtendedArray) interface
Use the Following code to remove all subviews.
If you want to remove all the subviews on your UIView (here
yourView
), then write this code at your button click:In order to remove all subviews from superviews:
This does only apply to OSX since in iOS a copy of the array is kept
When removing all the subviews, it is a good idea to start deleting at the end of the array and keep deleting until you reach the beginning. This can be accomplished with this two lines of code:
SWIFT 1.2
or (less efficient, but more readable)
NOTE
You should NOT remove the subviews in normal order, since it may cause a crash if a UIView instance is deleted before the
removeFromSuperview
message has been sent to all objects of the array. (Obviously, deleting the last element would not cause a crash)Therefore, the code
should NOT be used.
Quote from Apple documentation about makeObjectsPerformSelector:
(which would be the wrong direction for this purpose)