你可以在UIView上KVO属性gestureRecognizers吗?

时间:2014-07-31 00:55:37

标签: ios objective-c uiview key-value-observing

我正在创建UIView,可以更改添加到自身的gestureRecognizers。为了测试它,我在添加观察者后立即添加了一个轻击手势来触发KVO。

- (void)awakeFromNib
{
    [self addObserver:self forKeyPath:@"gestureRecognizers" options:NSKeyValueObservingOptionNew context:observeContext];
    [super awakeFromNib];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(test)];
    [self addGestureRecognizer:tap];

    [self createCircles];
}


- (void)test
{
    DDLogVerbose(@"got tapped");
}


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    DDLogVerbose(@"something got in here");
    if ([keyPath isEqualToString:@"gestureRecognizers"]) {
        DDLogVerbose(@"ThreeCirclesView got a gesture recognizer");
    }
}

然而,它不起作用。我这样做了吗?或者属性gestureRecognizers不是KVO能够的吗?

1 个答案:

答案 0 :(得分:1)

与大多数Apple的属性一样,我认为gestureRecognizers是不可观察的。但是,您可以在UIView子类中覆盖addGestureRecognizer:以便您可以响应添加,

-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    [super addGestureRecognizer:gestureRecognizer];
    NSLog(@"added a gr");
    // do whatever in ressponse to a new gesture recognizer being added
}

您可以使用removeGestureRecognizer执行相同操作:如果您还需要查看删除功能。