20
votes

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!

4
You know when a view gets removed, because you do it in code anyway? Just hook up your code there, or a helper function.Eiko

4 Answers

28
votes

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

27
votes

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.

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

You can subclass your UIView and post notifications from it's - (void)removeFromSuperview method.