What is the correct way to remove a subview from a

2019-03-09 04:26发布

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 this:

UIView *v = [self.containerView viewWithTag:[n integerValue]];

[v removeFromSuperview];

and got a bizarre result. Previously present UIViews disappeared as well. What's going on?

7条回答
在下西门庆
2楼-- · 2019-03-09 05:29

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
    }
}
查看更多
登录 后发表回答