美文网首页
iOS----block添加点击事件

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

作者: lizhi_boy | 来源:发表于2017-04-05 17:29 被阅读122次

之前有介绍通过委托代理的方式来添加视图的点击事件的操作,如果嫌麻烦的童鞋,通过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添加点击事件

      本文链接:https://www.haomeiwen.com/subject/oplxattx.html