如何删除所有子视图? [英] How to remove all subviews?

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

问题描述

当我的应用返回其根视图控制器时,在 viewDidAppear:方法中,我需要删除所有子视图.

When my app gets back to its root view controller, in the viewDidAppear: method I need to remove all subviews.

我该怎么做?

推荐答案

编辑:感谢 cocoafan:由于 NSView UIView 对事物的处理不同,因此使这种情况更加混乱.对于 NSView (仅适用于台式机Mac开发),您可以简单地使用以下代码:

With thanks to cocoafan: This situation is muddled up by the fact that NSView and UIView handle things differently. For NSView (desktop Mac development only), you can simply use the following:

[someNSView setSubviews:[NSArray array]];

对于 UIView (仅适用于iOS开发),您可以安全地使用 makeObjectsPerformSelector:,因为 subviews 属性将返回 copy 的子视图数组:

For UIView (iOS development only), you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the array of subviews:

[[someUIView subviews]
 makeObjectsPerformSelector:@selector(removeFromSuperview)];

感谢您汤米指出 makeObjectsPerformSelector:似乎在修改 subviews 数组(对于 NSView ,而不是 UIView ).

Thank you to Tommy for pointing out that makeObjectsPerformSelector: appears to modify the subviews array while it is being enumerated (which it does for NSView, but not for UIView).

有关更多详细信息,请参见此SO问题.

Please see this SO question for more details.

注意:(如果未保留在其他视图中),则使用这两种方法之一将删除主视图包含的每个视图并释放它们.来自 removeFromSuperview :

Note: Using either of these two methods will remove every view that your main view contains and release them, if they are not retained elsewhere. From Apple's documentation on removeFromSuperview:

如果接收方的超级视图不为零,则此方法将释放接收方.如果您打算重用该视图,请确保在调用此方法之前保留该视图,并确保在完成该视图或将其添加到另一个视图层次结构后适当地释放它.

If the receiver’s superview is not nil, this method releases the receiver. If you plan to reuse the view, be sure to retain it before calling this method and be sure to release it as appropriate when you are done with it or after adding it to another view hierarchy.

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

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