如何在Objective-C中删除子视图? [英] How to remove subviews in Objective-C?

查看:83
本文介绍了如何在Objective-C中删除子视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have added UIButton and UITextView as subviews to my view programmatically.

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];

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

I need to remove all subviews when the button is clicked.

我尝试过:

[self.view removeFromSuperView]

但是它不起作用.

推荐答案

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

I assume you're calling [self.view removeFromSuperView] from a method in the same class as the above snippet.

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

In that case [self.view removeFromSuperView] removes self.view from its own superview, but self is the object from whose view you wish to remove subviews. If you want to remove all the subviews of the object, you need to do this instead:

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

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

Perhaps you'd want to store those subviews in an NSArray and loop over that array invoking removeFromSuperview on each element in that array.

这篇关于如何在Objective-C中删除子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆