UITableView 自定义 cell 添加按钮点击事件 - iOS

使用 TableView 的时候经常会遇到自定义 cell 增加按钮并绑定事件的情况,如下是通过对自定义 cell 设置代理的方式实现,具体步骤如下:

首先,在自定义 cell.h 中设置代理;

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@protocol InvoiceRecordsListCellDelegate <NSObject>

- (void)invoiceRecordsListCellBtnClick:(UIButton *)btn; // 配置代理

@end

@class YHInvoiceRecordsListModel;
@interface YHInvoiceRecordsListCell : UITableViewCell

@property (nonatomic, weak) id <InvoiceRecordsListCellDelegate> delegate; // 声明代理

@property (nonatomic, strong) YHInvoiceRecordsListModel *model;

/// 抬头
@property (nonatomic, strong) UILabel *labTit;
/// 创建日期
@property (nonatomic, strong) UILabel *labDate;
/// 金额
@property (nonatomic, strong) UILabel *labPoints;
/// 状态
@property (nonatomic, strong) UILabel *labPayType;

/// Img 发送邮箱 & 申请重开
@property (nonatomic, strong) UIImageView *imgViewType;
@property (nonatomic, strong) UIButton *btnType;
/// 底部样式视图
@property (nonatomic, strong) UIView *viewFooter;

+ (instancetype)showInvoiceRecordsListCellWithTableView:(UITableView *)tabView;

@end

NS_ASSUME_NONNULL_END

其次,在 cell.m 中实现对按钮绑定事件中添加代理;

- (void)btnClick:(UIButton *)btn {
    btn.tag = self.tag; // 赋值按钮 tag,用于获取数据源中对应的数据
    NSLog(@"[点击事件] - Delegate - %ld - %ld", (long)self.tag, btn.tag);
    if ([_delegate respondsToSelector:@selector(invoiceRecordsListCellBtnClick:)]) {
        [_delegate invoiceRecordsListCellBtnClick:btn];
    }
}

最后,在控制视图中实现 cell 中的代理方法;

#pragma mark - ****************************** Delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YHInvoiceRecordsListModel *model = dataSource[indexPath.row];
    YHInvoiceRecordsListCell *cell = [YHInvoiceRecordsListCell showInvoiceRecordsListCellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    cell.delegate = self; // 配置代理 delegate
    cell.tag = indexPath.row; // 设置 tag
    return cell;
}

- (void)invoiceRecordsListCellBtnClick:(UIButton *)btn {
    // 按钮事件中实现具体业务即可
}

注:记得在 @interface 中继承代理协议


以上便是此次分享的全部内容,希望能对大家有所帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值