检查视图是否已被删除?
我有一个 UIView 类,目前正在通过在类 [self removeFromSuperview]
内部使用它来从我的视图中删除它。希望这是正确的做法。
但是,现在从我的视图控制器(我将这个视图添加到其中)我需要知道它何时删除自身,以便我可以在发生这种情况时调用一个方法。
I have a UIView class which I am currently removing from my view by using from inside the class [self removeFromSuperview]
. Hopefully that's the correct thing to do.
However, now from my view controller (of which I add this view to) I need to know when it has removed itself so that I can call a method when this happens.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
一般来说,视图不应该做诸如删除自身之类的事情。这就是视图控制器的工作。
如果 UIView 子类可以生成需要更改视图层次结构的事件,我将为该视图定义一个 delegate 属性,当事件发生时,调用一个方法那个代表。然后,当视图控制器添加视图时,它将自身设置为委托并定义相关方法来处理事件。
Generally speaking, the view shouldn't be doing things like removing itself. That's the job of the view controller.
If a
UIView
subclass can produce events that require the view hierarchy to be changed, I would define adelegate
property for that view, and when an event occurs, call a method on that delegate. Then, when your view controller adds the view, it would set itself as the delegate and define the relevant method to handle the event.如果您已删除 UIView,
您可以使用以下代码检查它是否存在:
If you have removed the UIView
you can check if it exists with the following code:
您可以使用委托回调将控制器设置为视图的委托。当您要删除视图时,请进行委托回调并在控制器中实现回调方法。
在我看来,“removeFromSuperview”总是倒退的……:(
You could have a delegate callback setting the controller as the view's delegate. When you're about to remove the view, make the delegate callback and implement the callback method in your controller.
The 'removeFromSuperview' has always seemed backwards to me… :(
我假设您在执行某种操作(例如按下按钮或其他操作)后进行删除调用。如果是这种情况,请将按钮委托设置为视图控制器,而不是视图类,并在视图控制器的操作方法内调用
I'm assuming you are making the remove call after some sort of action, like a button press or something. if that is the case, set the buttons delegate to be the view controller, not the view class, and inside the action method in the view controller, call
最好的选择是让控制器删除视图
,并了解视图是否被删除(或从未添加),您可以询问
The best choice would be to let the controller remove the view
and to know if the view was removed (or never added) you can ask
不确定你使用的是什么 sdk - 但我使用的是 iOS 5,我只是在超级视图中使用以下方法:
Not sure what sdk you are using - but I am using iOS 5 and I just use the following method in the superview: