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 U开发者_开发百科IView removed from its superView?I should use KVO? thanks in advance!
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.
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
- (void) willMoveToSuperview: (UIView *) newSuperview{
if(newSuperview == nil){
// UIView was removed from superview
} else {
// UIView was added to superview
}
}
You can subclass your UIView and post notifications from it's - (void)removeFromSuperview
method.
精彩评论