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

本文介绍如何在iOS开发中使用Block来处理TableViewController中的UITableViewCell按钮的点击事件,通过创建TableViewCell和TableViewController类,关联按钮与Block,实现按钮点击时执行特定操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家都知道在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.youkuaiyun.com/detail/kiushuo/7841155
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值