iOS Block 处理UITableViewCell上button的点击事件

大家都知道在cell上添加button的话并没有什么难处, 直接添加就是,难处在于怎样处理button的点击事件. 
 那么怎样处理点击事件呢?在这里通过block的方式来处理cell上的button的点击事件.

前提工作:新建一个工程,  创建一个TableViewController,在cell上添加一个button
这里为了方便起见,使用storyboard建立了一个tableViewController,往tableViewController的view上添加了一个cell, 
只是往cell上添加了一个button


分别创建一个继承于UITableViewController的类TableViewController,和继承于UITableViewCell的类TableViewCell,与storyboard中的tableViewController和cell关联
将cell上的label和button关联到TableViewCell的头文件中,并且将button的点击事件关联到TableViewCell的实现文件(.m)中
接下来就不多说了,直接上代码:


//TableViewCell的.h中:
#import

typedef void(^BlockButton)(NSString *str);

@interface TableViewCell : UITableViewCell
//与cell上的tittle(UILabel类型)关联
@property (strong, nonatomic) IBOutlet UILabel *title;
//与cell上的button关联
@property (strong, nonatomic) IBOutlet UIButton*buttonOnCell;
//block属性
@property (nonatomic, copy) BlockButton button;
//自定义block方法
- (void)handlerButtonAction:(BlockButton)block;

@end
//TableViewCell的.m中:
//与cell上的button关联的点击事件
- (IBAction)buttonOnCellAction:(UIButton *)sender {
 
    if(self.button) {
              self.button(self.buttonOnCell.titleLabel.text);
      }
}
//block的实现部分
- (void)handlerButtonAction:(BlockButton)block
{
      self.button= block;
}

//TableViewController的.m文件中: 其中self.arr 是一个定义为属性的可变数组 里边随意存储一些数据用来在button上显示
- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      TableViewCell *cell = [tableViewdequeueReusableCellWithI dentifier:@"buttonCell"forIndexPath:indexPath];
      cell.title.text = [NSString stringWithFormat:@"%d",indexPath.row];
      [cell.buttonOnCell setTitle:[self.arr objectAtIndex:indexPath.row]forState:UIControlStateNormal];
      [cellhandlerButtonAction:^(NSString *str) {
              NSLog(@"====%@", str);
      }];
      // Configurethe cell...
     
      returncell;
}



下载工程地址:http://download.csdn.net/detail/kiushuo/7841155
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值