26

我以编程方式将 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]

但它不起作用。

4

3 回答 3

59

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

使用以下代码

for (UIView *view in [self.view subviews]) 
{
    [view removeFromSuperview];
}
于 2010-06-09T12:49:32.490 回答
23

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

在这种情况下[self.view removeFromSuperView],从它自己的父视图中删除 self.view,但 self 是您希望从其视图中删除子视图的对象。如果要删除对象的所有子视图,则需要这样做:

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

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

于 2010-06-09T12:05:43.793 回答
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)];

我更喜欢那个。

于 2014-02-21T06:07:03.110 回答