UITableView详解(UITableViewCell(二) 自定义cell)

     上一节中,我们定义的cell比较单一,只是单调的输入文本和插入图片,但是在实际开发中,有的cell上面有按钮,有的cell上面有滑动控件,有的cell上面有开关选项等等,具体参加下面2个图的对比:

@我们可以通过2种方式来实现自定义,一是利用系统的UITableViewCell(但不推荐,因为开发效率不高),举例:还是在这个关键方法中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * cellIdentifier  = @"cell";

    UITableViewCell * cell = [tableViewdequeueReusableCellWithIdentifier:cellIdentifier];

    if (!cell) {

        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentifier];

     // 首先,各种按钮控件的初始化,一定要放在这个if语句里面,如果放在这个大括号外面,cell被执行n次,那么一个cell上面就会被添加n个控件

     // 其次,你在这个括号里面自定义初始化控件后,如果你想给每一个cell的控件显示不同的内容和效果,你在括号外面是取不到对象的,只有通过设置它们继承UIView的属性tag来标识,我们可以想一想,如果控件一多或者别人来接受你的项目,你自己定义了很多的tag,这样合作的效率不高,所以主要推荐第二种

    }

    return cell;

}

@二是,创建UITableViewCell子类,在contentView上实现自定义效果(cell上的所有内容都是显示在cell的属性contentView上),这里也是写这个方法

#import <UIKit/UIKit.h>

@interface HMTAssistCell : UITableViewCell

@property (nonatomic) UILabel * label;
@property (nonatomic) UIButton * button;

@end

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        _button = [UIButton buttonWithType:UIButtonTypeSystem];
        _button.backgroundColor = [UIColor redColor];
        _button.frame = CGRectMake(150, 60, 50, 100);
        [_button setTitle:@"油条" forState:UIControlStateNormal];
        [self.contentView addSubview:_button];
        
        _label = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, 100, 100)];
        _label.backgroundColor = [UIColor greenColor];
        [self.contentView addSubview:_label];
 
        
    }
    return self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // 依旧设置重用标识
    static NSString * cellIdentifier  = @"cell";
    
    // 这里用我们新建的UITableViewCell的子类进行cell重用声明
    HMTAssistCell * cell = (HMTAssistCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    // 如果没有,则创建
    if (!cell) {
        
        cell = [[HMTAssistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    // 因为_label是类HMTAssistCell中的属性,所以就能很方便的取出来进行赋值
    cell.label.text = [NSString stringWithFormat:@"%d",indexPath.row];

    return cell;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值