iOS DeveloperiOS 开发成长中心iOS 你不知道的新鲜事

iOS开发--Block传递按钮点击事件

2016-11-16  本文已影响3418人  爱吃鱼的小灰
// 用typef宏定义来减少冗余代码
typedef void(^ButtonClick)(UIButton * sender);// 这里的index是参数,我传递的是button的tag值,当然你可以自己决定传递什么参数
//下一步就是声明属性了,注意block的声明属性修饰要用copy
@property (nonatomic,copy) ButtonClick buttonAction;

到此.h文件大致就是这了

  - (void)buttonClick:(UIButton *)button{
// 判断下这个block在控制其中有没有被实现
    if (self.buttonAction) {
// 调用block传入参数
        self.buttonAction(button);
    }
}
// 在创建cell的时候
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JHTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (cell == nil) {
        cell = [[JHTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
    }
// 就在这里cell初始化成功后去给Block赋值调用它的setter方法
    cell.buttonAction = ^(UIButton *sender){
         [self cellButtonClick:sender];// 在Block内部去调用一个方法,当然你也可以直接在这里写,只要你不嫌代码臃肿
    };
    return cell;
}
// 将方法抽出来放在外边看起来不至于让tableView的代理方法太臃肿
  - (void) cellButtonClick:(UIButton *)button
{
// 这里就可以实现点击后的后续操作了
}
上一篇 下一篇

猜你喜欢

热点阅读