iOS----block添加点击事件

之前有介绍通过委托代理的方式来添加视图的点击事件的操作,如果嫌麻烦的童鞋,通过block的方式添加点击事件会更加简便(组要是少写了许多代码),具体实现方式如下:

1、首先声明一个block对象

typedef void(^SelectTest)(UIButton *testButton);//给个别名

@interface wcCell : UITableViewCell
@property (nonatomic, copy) SelectTest selectBlock;
@end

2、在.m文件中给你要实现点击的事件的视图添加方法

视图添加方法:
       _wcLabel.userInteractionEnabled = YES;//告诉系统这个label是可以点击的
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testTap:)];
        [_wcLabel addGestureRecognizer:tap];

方法实现:
-(void)testTap:(UIButton *)sender{
    self.selectBlock(sender);
 }

3、在控制器中引用一下block就可以啦虹吸

    __block wcCell *cell1 = cell;//防止循环引用
    cell1.selectBlock = ^(UIButton *testButton) {
        NSLog(@"你点击了这个按钮");
    };

有帮助到你的童鞋,点击❤️,谢谢了

你可能感兴趣的:(iOS----block添加点击事件)