removeFromSuperview删除所有子视图

时间:2012-08-20 14:32:41

标签: iphone objective-c ios

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"will rotation");

    for (UIButton *button in self.view.subviews) {
        [button removeFromSuperview];
    }

}

我的代码有问题。我需要从我的视图中删除UIButtons。但是这段代码也删除了我的self.view的所有子视图。我该如何解决这个问题?

5 个答案:

答案 0 :(得分:5)

这样做:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
NSLog(@"will rotation");

   for (id subview in self.view.subviews) {
    if([subview isKindOfClass:[UIButton class]]) //remove only buttons
    {
      [subview removeFromSuperview];
    }
   }

}

答案 1 :(得分:4)

您正在迭代所有视图并将它们转换为UIButton,而不是迭代UIButton。 试试这个:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"will rotation");

    for (UIView *button in self.view.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [button removeFromSuperview];
        }        
    }
}

答案 2 :(得分:3)

for (id button in self.view.subviews) 
    {
        if(button isKindOfClass:[UIButton class])
        {
          [button removeFromSuperview];
        }
    }

答案 3 :(得分:2)

self.view.subviews将获取所有子视图,并且以这种方式使用类型UIButton *不会过滤列表,它只是向编译器提示您希望能够像UIButton一样处理对象。你必须检查每一个,如下所示:

for (UIView *subview in self.view.subviews) {
    if([subview isKinfOfClass:[UIButton class]])
      [subview removeFromSuperview];
}

答案 4 :(得分:0)

一种选择是在文件顶部创建一个标签

#define BUTTONSTODELETE 123

然后设置每个buttons.tag = BUTTONSTODELETE

最后:

for (UIButton *v in [self.view subviews]){
        if (v.tag == BUTTONSTODELETE) {
            [v removeFromSuperview];

保证只删除带有该标签的商品

编辑:Maulik和fbernardo有一个更好,更不凌乱的方式