问题
Is there a way to catch an event or notification if a view was added as subview to an existing view of a controller? I have a library here and I cannot subclass but need to know if a specific subview was added to trigger a custom action. Is there a chance?
回答1:
Not that I think this method is cleaner than the one @tiguero suggested, but I think it's slightly safer (see why using categories could be dangerous in my comments to his answer) and offers you more flexibilty.
This is somehow, although not exactly, but more at the conceptual level, the same way KVO works. You basically, dynamically alter the implementation of willMoveToSuperview
and add your notification code to it.
//Makes views announce their change of superviews
Method method = class_getInstanceMethod([UIView class], @selector(willMoveToSuperview:));
IMP originalImp = method_getImplementation(method);
void (^block)(id, UIView*) = ^(id _self, UIView* superview) {
[_self willChangeValueForKey:@"superview"];
originalImp(_self, @selector(willMoveToSuperview:), superview);
[_self didChangeValueForKey:@"superview"];
};
IMP newImp = imp_implementationWithBlock((__bridge void*)block);
method_setImplementation(method, newImp);
回答2:
I will try adding a category for the didAddSubview
method.
EDIT
Category is an alternative to subclassing so you could use something along those lines:
.h:
#import <UIkit/UIKit.h>
@interface UIView (AddSubView)
- (void)didAddSubview:(UIView *)view
@end
.m:
@implementation UIView (AddSubView)
- (void)didAddSubview:(UIView *)view
{
[self addSubview: view];
// invoke the method you want to notify the addition of the subview
}
@end
来源:https://stackoverflow.com/questions/14124810/without-subclassing-a-uiview-or-uiviewcontroller-possible-to-catch-if-a-subview