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

来源:互联网 发布:软件开发部门管理制度 编辑:程序博客网 时间:2024/04/30 20:40
大家都知道在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 = [tableViewdequeueReusableCellWithIdentifier:@"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 0