父view中添加手勢子view不響應問題的解決

// 父類view
    UIImageView *back = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    back.image = [UIImage imageNamed:@"Default-568h@2x"];
    back.userInteractionEnabled = YES;
    [self.view addSubview:back];
   
    // 父類view中的imageView
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"Default-568h@2x"];
    imageView.userInteractionEnabled = YES;
   
    // 父類view中的label
    label = [[UILabel alloc] initWithFrame:CGRectMake(100, 240, 100, 100)];
    label.text = @"label";
    label.backgroundColor = [UIColor grayColor];
    // 此屬性必須打開,否則UITouch捕獲Label
    label.userInteractionEnabled = YES;
   
    // 父類view中的button
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"button" forState:UIControlStateNormal];
    button.frame = CGRectMake(100, 350, 100, 100);
    button.backgroundColor = [UIColor purpleColor];
    [button addTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];

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

    [back addGestureRecognizer:tap];
    [back addSubview:imageView];
    [back addSubview:label];
    [back addSubview:button];
}
- (void)btn
{
    NSLog(@"button");ide

}spa

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 取消labelimageview響應手勢
    if ([touch.view isKindOfClass:[UILabel class]] || touch.view == imageView)
    {
        return NO;
    }
    return YES;

}
- (void)tap:(UITapGestureRecognizer *)tap
{
    NSLog(@"tap.view = %@",tap.view);
}3d

相關文章
相關標籤/搜索