0

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?

4

2 回答 2

2

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

编辑

类别是子类化的替代方法,因此您可以使用以下内容:

。H:

  #import <UIkit/UIKit.h>

  @interface UIView (AddSubView)

  - (void)didAddSubview:(UIView *)view

  @end

米:

@implementation UIView (AddSubView)
- (void)didAddSubview:(UIView *)view
{
     [self addSubview: view];

     // invoke the method you want to notify the addition of the subview

}
@end
于 2013-01-02T15:46:18.250 回答
1

并不是说我认为这种方法比@tiguero 建议的方法更干净,但我认为它更安全(请参阅为什么在我对他的回答的评论中使用类别可能是危险的)并为您提供更多的灵活性。

这在某种程度上,虽然不完全是,但更多的是在概念层面上,与 KVO 的工作方式相同。基本上,您可以动态更改通知代码的实现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);
于 2013-01-02T17:03:38.403 回答