简体   繁体   English

如何在UIView与superView分离时收到通知?

[英]How to be notified when a UIView detached from its superView?

It seems that the UIView has not methods like " didRemoveFromSuperview " or " willRemoveFromSuperview ".Then,How to listen to the event when a UIView removed from its superView?I should use KVO? 似乎UIView没有像“ didRemoveFromSuperview ”或“ willRemoveFromSuperview ”这样的方法。那么,当UIView从其superView中删除时如何监听事件?我应该使用KVO? thanks in advance! 提前致谢!

This topic is quite old, but I found a way to do it .Since google search wasn't helpful enough, here it is (taken from UIView's docs) 这个话题已经很老了,但我找到了一种方法。由于谷歌搜索不够有用,这里是(取自UIView的文档)

Observing View-Related Changes 观察与视图相关的更改

– didAddSubview: - didAddSubview:

– willRemoveSubview: - willRemoveSubview:

– willMoveToSuperview: - willMoveToSuperview:

– didMoveToSuperview - didMoveToSuperview

– willMoveToWindow: - willMoveToWindow:

– didMoveToWindow - didMoveToWindow

This works (tested on iOS8): 这有效(在iOS8上测试):

-(void) didMoveToWindow {
    [super didMoveToWindow]; // (does nothing by default)
    if (self.window == nil) {
        // YOUR CODE FOR WHEN UIVIEW IS REMOVED
    }
}

According to the UIView docs : 根据UIView文档

The default implementation of this method does nothing. 此方法的默认实现不执行任何操作。 Subclasses can override it to perform additional actions whenever the window changes. 子窗口可以覆盖它,以便在窗口更改时执行其他操作。

The window property may be nil ... This occurs when the receiver has just been removed from its superview or when the receiver has just been added to a superview that is not attached to a window. 窗口属性可能是nil ... 当接收器刚刚从其超级视图中移除时或者刚刚将接收器添加到未附加到窗口的超级视图时,会发生这种情况。

您可以将UIView子类化并从中发布通知- (void)removeFromSuperview方法。

- (void) willMoveToSuperview: (UIView *) newSuperview{
    if(newSuperview == nil){
        // UIView was removed from superview
    } else {
        // UIView was added to superview
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM