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

27

我已经以编程方式将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个回答

59

使用以下代码可以删除您添加到视图中的所有子视图

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

23
我假设你正在从与上面片段相同的类中调用[self.view removeFromSuperView]
在这种情况下,[self.view removeFromSuperView] 会将 self.view 从其自身的父视图中删除,但是你想要删除子视图的对象是 self。如果你想要删除对象的所有子视图,你需要使用以下代码:
[notesDescriptionView removeFromSuperview];
[button.view removeFromSuperview];
[textView removeFromSuperview];

你也许想把这些子视图存储在一个 NSArray 中,并循环遍历该数组,在每个元素上调用 removeFromSuperview


关于我创建的按钮,作为子视图添加进去的问题,您怎么看?实际上,我正在尝试在按钮按下后显示一个带有TextView的视图,然后当我点击当前视图中的另一个按钮时,它应该返回到我的先前视图。 - mac
我已经尝试了 [notesDescriptionView removeFromSuperview]; [textView removeFromSuperview]; 但是它没有起作用。 - mac
什么是从另一个类中删除子视图的正确方法调用?我尝试使用代理方法,但它不起作用。 - SanitLee

8

我一直很惊讶,Objective-C API 没有一个简单的方法来从 UIView 中移除所有子视图。(Flash API 有这个功能,你会经常需要它。)

无论如何,我使用的小辅助方法如下:

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

编辑:在这里找到了一种更优雅的解决方案:什么是从self.view中删除所有子视图的最佳方法?

现在我正在使用以下方法:

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

我更喜欢那个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接