Remove all subviews?


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?


In order to remove all subviews from superviews:

NSArray *oSubView = [self subviews];
for(int iCount = 0; iCount 
By : Pravin

For ios6 using autolayout I had to add a little bit of code to remove the constraints too.

NSMutableArray * constraints_to_remove = [ @[] mutableCopy] ;
for( NSLayoutConstraint * constraint in tagview.constraints) {
    if( [tagview.subviews containsObject:constraint.firstItem] ||
       [tagview.subviews containsObject:constraint.secondItem] ) {
        [constraints_to_remove addObject:constraint];
[tagview removeConstraints:constraints_to_remove];

[ [tagview subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

I'm sure theres a neater way to do this, but it worked for me. In my case I could not use a direct [tagview removeConstraints:tagview.constraints] as there were constraints set in XCode that were getting cleared.

If you're using Swift, it's as simple as: { $0.removeFromSuperview }

It's similar in philosophy to the makeObjectsPerformSelector approach, however with a little more type safety.

By : lms

This video can help you solving your question :)
By: admin