Remove all subviews?

前端 未结 15 1607

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?

相关标签:
15条回答
  • 2020-11-28 00:48

    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.

    0 讨论(0)
  • 2020-11-28 00:49

    Try this way swift 2.0

    view.subviews.forEach { $0.removeFromSuperview() }
    
    0 讨论(0)
  • 2020-11-28 00:49

    In objective-C, go ahead and create a category method off of the UIView class.

    - (void)removeAllSubviews
    {
        for (UIView *subview in self.subviews)
            [subview removeFromSuperview];
    }
    
    0 讨论(0)
  • 2020-11-28 00:51

    Use the Following code to remove all subviews.

    for (UIView *view in [self.view subviews]) 
    {
     [view removeFromSuperview];
    }
    
    0 讨论(0)
  • 2020-11-28 00:51

    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.

    0 讨论(0)
  • 2020-11-28 00:51

    In order to remove all subviews from superviews:

    NSArray *oSubView = [self subviews];
    for(int iCount = 0; iCount < [oSubView count]; iCount++)
    {
        id object = [oSubView objectAtIndex:iCount];
        [object removeFromSuperview];
        iCount--;
    }
    
    0 讨论(0)
提交回复
热议问题