没有子类UIView或UIViewController:可能捕获子视图是否被添加?

如果视图作为子视图添加到控制器的现有视图,是否有办法捕获事件或通知? 我在这里有一个库,我不能inheritance子类,但需要知道是否添加了特定的子视图来触发自定义操作。 有机会吗?

不是我认为这个方法比@tiguerobuild议的方法更清洁,但是我认为这样比较安全一些(看看为什么在我的评论中使用类别可能是危险的),并且给你更多的灵活性。

这虽然不尽如人意,但更多的是在概念层面,就像KVO的工作方式一样。 基本上,dynamic地改变willMoveToSuperview的实现,并将通知代码添加到它。

 //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); 

我将尝试为didAddSubview方法添加一个类别。

编辑

类别是子类别的一种替代方法,所以你可以使用这些方法:

。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