天天看點

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

// 父類 view

    UIImageView *back = [[ UIImageView alloc ] initWithFrame : CGRectMake ( 0 , 0 , kScreenWidth , kScreenHeight )];

    back. image = [ UIImage imageNamed : @"[email protected]" ];

    back. userInteractionEnabled = YES ;

    [ self . view addSubview :back];

    // 父類 view 中的 imageView

    imageView = [[ UIImageView alloc ] initWithFrame : CGRectMake ( 100 , 100 , 100 , 100 )];

    imageView . image = [ UIImage imageNamed : @"[email protected]" ];

    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" ); } - ( BOOL )gestureRecognizer:( UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:( UITouch *)touch

{

    // 取消 label 和 imageview 響應手勢

    if ([touch. view isKindOfClass :[ UILabel class ]] || touch. view == imageView )

    {

        return NO ;

    }

    return YES ;

}

- ( void )tap:( UITapGestureRecognizer *)tap

{

    NSLog ( @"tap.view = %@" ,tap. view );

}