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

mac*_*mac 26 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];
Run Code Online (Sandbox Code Playgroud)

我需要在单击按钮时删除所有子视图.

我试过了:

[self.view removeFromSuperView]
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

mac*_*mac 59

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

使用以下代码

for (UIView *view in [self.view subviews]) 
{
    [view removeFromSuperview];
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*rar 23

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

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

[notesDescriptionView removeFromSuperview];
[button.view removeFromSuperview];
[textView removeFromSuperview];
Run Code Online (Sandbox Code Playgroud)

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


Eri*_*eut 8

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

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

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

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

我现在使用如下:

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

我更喜欢这样.