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

14,516

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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

Share:
14,516
Jagie
Author by

Jagie

hi,I am Jagie. I specialize in mobile-platform programming such as WM,iPhone and Android. I also do ActionScript and Java.

Updated on June 18, 2022

Comments

  • Jagie
    Jagie about 2 years

    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!

  • Jagie
    Jagie about 14 years
    I find.Api doc says: willMoveToSuperview: Informs the receiver that its superview is about to change to the specified superview (which may be nil). ----------------------------------------- When this method is called and the parameter is nil, the view is being removed
  • dedda1994
    dedda1994 almost 5 years
    This is not what was asked for. In the question it is clearly stated that there are no methods to get notified when the view was removed from it's superview. This might be a list of the view hierarchy change methods the UIView class has but does not provide any method for the use case that was asked for.
  • floydaddict
    floydaddict over 3 years
    "In the question it is clearly stated that there are no methods to get notified when the view was removed from it's superview" you know sometimes the person who ask a question can be wrong, furthermore it's not "clearly stated". The answer is correct you can check if a view is removed in didMoveToSuperview (if superview is nil) or in didMoveToWindow (if window is nil)