从视图层次结构中删除子视图的正确方法是什么? [英] What is the correct way to remove a subview from a view hierarchy and nuke it?

查看:170
本文介绍了从视图层次结构中删除子视图的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父UIView与一些子视图。定期我需要删除一个子视图,并从系统中完全删除它。什么是正确的方法这样做?我尝试这样:

  UIView * v = [self.containerView viewWithTag:[n integerValue]]; 

[v removeFromSuperview];

得到了一个奇怪的结果。以前存在 UIView 也消失了。发生了什么?

解决方案

尝试:

  UIView * v = [self.containerView viewWithTag:[n integerValue]]; 
v.hidden = YES;
[self.containerView bringSubviewToFront:v];
[v removeFromSuperview];另一件事我从UIView类文档中注意到 - 看到最后一句话:


b
$ b

removeFromSuperview
取消将接收器从其超级视图及其窗口中断开,并将其从响应器链中删除。




  • (void)removeFromSuperview



讨论
如果接收者的superview不为nil, 。如果您计划重用此视图,请务必在调用此方法之前保留此视图,并确保在完成视图或将其添加到其他视图层次结构后适当地释放视图。



从不在显示时调用此方法



更新:现在是2014, 。原始海报的代码应该按原样工作:

  UIView * v = [self.containerView viewWithTag:[n integerValue]]; 
[v removeFromSuperview];

这将删除v和它附加到它作为子视图的任何视图,留下containerView和任何兄弟姐妹of v。


I have a parent UIView with a number of subviews. Periodically I need to remove a subview and completely remove it from the system. What is the correct way to do this? I tried this:

UIView *v = [self.containerView viewWithTag:[n integerValue]];

[v removeFromSuperview];

and got a bizarre result. Previously present UIViews disappeared as well. What's going on?

解决方案

Try this:

UIView *v = [self.containerView viewWithTag:[n integerValue]];
v.hidden = YES;
[self.containerView bringSubviewToFront:v];
[v removeFromSuperview];

Another thing I just noticed from the UIView class document - see the last sentence:

removeFromSuperview Unlinks the receiver from its superview and its window, and removes it from the responder chain.

  • (void)removeFromSuperview

Discussion 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.

Never invoke this method while displaying.

UPDATE: It is now 2014 and removing a subview without hiding it works perfectly fine. The original poster's code should work as-is:

UIView *v = [self.containerView viewWithTag:[n integerValue]];
[v removeFromSuperview];

This will remove v and any views it has attached to it as subviews, leaving behind containerView and any siblings of v.

这篇关于从视图层次结构中删除子视图的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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