What is the correct way to remove a subview from a view hierarchy and nuke it?

后端 未结 8 1448
走了就别回头了
走了就别回头了 2021-01-31 15:34

I have a parent UIView with a number of subviews. Periodically I need to remove a subview and completely remove it from the system. What is the correct way to do this? I tried t

8条回答
  •  深忆病人
    2021-01-31 15:58

    To remove all subviews from your view:

    for(UIView *subview in [view subviews]) {
       [subview removeFromSuperview];
    }
    

    If you want to remove some specific view only then:

    for(UIView *subview in [view subviews]) {
      if([subview isKindOfClass:[UIButton class]]) {
         [subview removeFromSuperview];
     } else {
         // Do nothing - not a UIButton or subclass instance
     }
    }
    

    You can also delete sub views by tag value:

    for(UIView *subview in [view subviews]) {
        if(subview.tag==/*your subview tag value here*/) {
            [subview removeFromSuperview];
    
        } else {
            // Do nothing - not a UIButton or subclass instance
        }
    }
    

提交回复
热议问题