0

ビューがコントローラーの既存のビューにサブビューとして追加された場合に、イベントまたは通知をキャッチする方法はありますか?ここにライブラリがあり、サブクラス化できませんが、カスタムアクションをトリガーするために特定のサブビューが追加されたかどうかを知る必要があります。チャンスはありますか?

4

2 に答える 2

2

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
于 2013-01-02T15:46:18.250 に答える
1

この方法は@tigueroが提案した方法よりもクリーンだとは思いませんが、少し安全だと思います(彼の回答に対する私のコメントで、カテゴリの使用が危険な理由を参照してください)。

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);
于 2013-01-02T17:03:38.403 に答える