如何删除Objective-C中的子视图?

时间:2010-06-09 11:57:55

标签: objective-c subview

我已经以编程方式将UIButton和UITextView作为子视图添加到我的视图中。

notesDescriptionView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)];
notesDescriptionView.backgroundColor = [UIColor redColor];
[self.view addSubview:notesDescriptionView];

textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,320,420)]; 
[self.view addSubview:textView]; 
printf("\n description  button \n");

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button
  addTarget:self action:@selector(cancel:)
  forControlEvents:UIControlEventTouchDown];
[button setTitle:@"OK" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 420.0, 160.0, 40.0);
[self.view addSubview:button];

单击按钮时,我需要删除所有子视图。

我试过了:

[self.view removeFromSuperView]

但它不起作用。

3 个答案:

答案 0 :(得分:58)

删除您添加到视图中的所有子视图

使用以下代码

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

答案 1 :(得分:21)

我假设您从与上述代码段相同的类中的方法调用[self.view removeFromSuperView]

在这种情况下,[self.view removeFromSuperView]会从自己的超级视图中删除self.view,但self是您希望删除子视图的对象。如果要删除对象的所有子视图,则需要执行此操作:

[notesDescriptionView removeFromSuperview];
[button.view removeFromSuperview];
[textView removeFromSuperview];

也许您希望将这些子视图存储在NSArray中并循环遍历该数组,并在该数组中的每个元素上调用removeFromSuperview

答案 2 :(得分:7)

我一直很惊讶Objective-C API没有一个从UIView中删除所有子视图的简单方法。 (Flash API确实如此,你最终需要它。)

无论如何,这是我用来做的小助手方法:

- (void)removeAllSubviewsFromUIView:(UIView *)parentView
{
  for (id child in [parentView subviews])
  {
    if ([child isMemberOfClass:[UIView class]])
    {
      [child removeFromSuperview];
    }
  }
}

编辑:刚刚在这里找到了一个更优雅的解决方案:What is the best way to remove all subviews from you self.view?

现在使用如下:

  // Make sure the background and foreground views are empty:
  [self.backgroundContentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
  [self.foregroundContentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

我更喜欢这样。