一:使用XIB自定义Cell
方法一:生成cell过程中,
使用viewWithTag获取控制器,再通过addTarget 监听事件
// 通过xib文件来加载cell
NSBundle *bundle = [NSBundle mainBundle];
NSArray *objs = [bundle loadNibNamed:@"BookCell" owner:nil options:nil];
cell = [objs lastObject];
// 绑定监听器
UIButton *collect = (UIButton *)[cell viewWithTag:3];
[collect addTarget:self action:@selector(collectBook:event:) forControlEvents:UIControlEventTouchUpInside];
方法二:使用File‘s owner
3、新建类(继承UITableViewCell)
#import <UIKit/UIKit.h>
@interface BookCell : UITableViewCell
// readonly只生成get方法z
@property (nonatomic, weak, readonly) IBOutlet UILabel *nameLabel;
@property (nonatomic, weak, readonly) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic, readonly) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic, readonly) IBOutlet UIButton *buyBtn;
@end
#pragma mark 每当有一个cell进入视野范围内就会调用,返回当前这行显示的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 0.用static修饰的局部变量,只会初始化一次
static NSString *ID = @"Cell";
// 1.拿到一个标识先去缓存池中查找对应的Cell
BookCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
// 2.如果缓存池中没有,才需要传入一个标识创建新的Cell
if (cell == nil) {
// 通过xib文件来加载cell
NSBundle *bundle = [NSBundle mainBundle];
// 由于没有用到xib文件中的Owner,所以这里的owner传nil即可
NSArray *objs = [bundle loadNibNamed:@"BookCell" owner:nil options:nil];
cell = [objs lastObject];
// 给按钮绑定监听器
//[cell.collectBtn addTarget:<#(id)#> action:<#(SEL)#> forControlEvents:<#(UIControlEvents)#>];
//[cell.buyBtn addTarget:<#(id)#> action:<#(SEL)#> forControlEvents:<#(UIControlEvents)#>];
NSLog(@"%@", cell);
}
// 3.覆盖数据
// 3.1 取出本行的book对象
Book *b = self.books[indexPath.row];
// 设置书名
cell.nameLabel.text = b.name;
// 设置价格
cell.priceLabel.text = [NSString stringWithFormat:@"¥%.1f", b.price];
return cell;
}
二:使用代码自定义Cell:再自己的类中初始化cell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// 添加子控件
}
return self;
}