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

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

}

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

4

5 回答 5

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];
    }
   }

}
于 2012-08-20T14:35:44.653 回答
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];
        }        
    }
}
于 2012-08-20T14:36:14.627 回答
3
for (id button in self.view.subviews) 
    {
        if(button isKindOfClass:[UIButton class])
        {
          [button removeFromSuperview];
        }
    }
于 2012-08-20T14:36:00.177 回答
2

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

for (UIView *subview in self.view.subviews) {
    if([subview isKinfOfClass:[UIButton class]])
      [subview removeFromSuperview];
}
于 2012-08-20T14:38:02.450 回答
0

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

#define BUTTONSTODELETE 123

然后设置每个buttons.tag = BUTTONSTODELETE

最后 :

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

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

编辑:Maulik 和 fbernardo 有一种更好、更简洁的方式

于 2012-08-20T14:37:50.313 回答