一:使用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;
}