【问题标题】:How to remove subviews in Objective-C?如何在 Objective-C 中删除子视图?
【发布时间】:2010-06-09 11:57:54
【问题描述】:

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

但它不起作用。

【问题讨论】:

    标签: objective-c subview


    【解决方案1】:

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

    使用以下代码

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

    【讨论】:

      【解决方案2】:

      我假设您从与上述 sn-p 相同的类中的方法调用 [self.view removeFromSuperView]

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

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

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

      【讨论】:

      • 我创建的按钮怎么样,通过添加为子视图。实际上我正在尝试使用 textview 显示一个视图,当按下按钮时,当我单击当前视图中的另一个按钮后,它必须返回我以前的视图。
      • 我试过 [notesDescriptionView removeFromSuperview]; [textView removeFromSuperview];但它不起作用。
      • 调用这种从其他类的父视图中删除子视图的方法的正确方法是什么?我正在尝试委托方法,但它不起作用。
      【解决方案3】:

      我一直对 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)];
      

      我更喜欢这样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-10
        相关资源
        最近更新 更多