使用 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 中继承代理协议
以上便是此次分享的全部内容,希望能对大家有所帮助!
网友评论