简体   繁体   中英

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? 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)

Observing View-Related Changes

– didAddSubview:

– willRemoveSubview:

– willMoveToSuperview:

– didMoveToSuperview

– willMoveToWindow:

– didMoveToWindow

This works (tested on 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 :

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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