从视图层次结构中删除子视图并将其核对的正确方法是什么?

dug*_*gla 38 cocoa-touch subview uiview ios

我有一个父UIView有很多子视图.我需要定期删除子视图并将其从系统中完全删除.这样做的正确方法是什么?我试过这个:

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

[v removeFromSuperview];
Run Code Online (Sandbox Code Playgroud)

并得到一个奇怪的结果.之前的礼物也UIView消失了.这是怎么回事?

mah*_*udz 68

试试这个:

UIView *v = [self.containerView viewWithTag:[n integerValue]];
v.hidden = YES;
[self.containerView bringSubviewToFront:v];
[v removeFromSuperview];
Run Code Online (Sandbox Code Playgroud)

我刚刚从UIView类文档中注意到的另一件事 - 请看最后一句:

removeFromSuperview取消接收器与其superview及其窗口的链接,并将其从响应器链中删除.

  • (空隙)removeFromSuperview

讨论如果接收者的超级视图不是零,则此方法释放接收者.如果您计划重用该视图,请确保在调用此方法之前保留该视图,并确保在完成该视图或将其添加到另一个视图层次结构后适当地释放它.

在显示时不要调用此方法.

更新:现在是2014年,删除子视图而不隐藏它可以很好地完成.原始海报的代码应按原样运作:

UIView *v = [self.containerView viewWithTag:[n integerValue]];
[v removeFromSuperview];
Run Code Online (Sandbox Code Playgroud)

这将删除v及其作为子视图附加到它的任何视图,留下containerView和v的任何兄弟.


iKu*_*hal 38

要从视图中删除所有子视图:

for(UIView *subview in [view subviews]) {
   [subview removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)

如果您只想删除某些特定视图:

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

您还可以按标记值删除子视图:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我比接受的答案更喜欢这个.这似乎是一个更直接的方法 - 你非常彻底,包括选择任何人可能想要删除的选项.+1. (3认同)