Xcode控件使用笔记四:UITableView-自定义Cell

本文介绍了如何在Xcode中自定义UITableViewCell。首先,我们可以通过XIB文件创建并设置Cell,利用viewWithTag获取控制器并添加目标来监听事件。接着,详细讲解了在自定义的UITableViewCell子类中初始化Cell的方法,实现更灵活的定制。

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值