随意细解:UI -- 自定义TableViewCell

本文详细介绍了如何自定义UITableView的Cell,包括自定义cell的四个步骤,如何混合使用不同类型的cell,以及实现cell自适应高度的具体方法和示例代码。通过自定义,可以满足更复杂的UI展示需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义TableViewCell

自定义cell步骤

(只要是自定义控件 都这个步骤)
1.创建TableViewCell子类
2.重写初始化方法
3.把要添加的控件 添加到cell的现实内容区域 contentView上面
4.把系统的cell替换成自定义cell 完成

这里写图片描述

注:要改变cell的高度

  1. 创建TableViewCell子类,并设置属性

    ```
    // MyTableViewCell.h文件:
    @property (nonatomic, retain) UIImageView *imageV;
    @property (nonatomic, retain) UILabel *nameLabel;
    @property (nonatomic, retain) UILabel *phoneLabel;
    @property (nonatomic, retain) UILabel *genderLabel;
    
    @property (nonatomic, retain) CellModel *model;
    ```
    
  2. 重写初始化方法,把要添加的控件 添加到cell的现实内容区域 contentView上面

        - (void)dealloc
        {
            [_imageV release];
            [_nameLabel release];
            [_phoneLabel release];
            [_genderLabel release];
            [_model release];
            [super dealloc];
        }
    
    - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
        [self addSubview];
        }
        return self;
    }
    // 添加子视图
    - (void)addSubview
    {
        self.imageV = [[UIImageView alloc]initWithFrame:CGRectMake(kMargin, kMargin, kImageWidth, kImageHeight)];
        self.imageV.backgroundColor = [UIColor yellowColor];
        [self.contentView addSubview:self.imageV];
        [self.imageV release];
    
        self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(kMargin * 2 + kImageWidth, kMargin, kScreenWidth - kImageWidth - kMargin * 3, (kImageHeight  - 2 * kLabelMargin) / 3)];
        self.nameLabel.backgroundColor = [UIColor blueColor];
        [self.contentView addSubview:self.nameLabel];
        [self.nameLabel release];
    
    .....//此处省略其他两个label
    
    }
    
    // 重写model的set方法,使赋值model的同时也对控件进行赋值
    - (void)setModel:(CellModel *)model
    {
        if (_model != model) {
            [_model release];
            _model = [model retain];
        }
        self.nameLabel.text = model.name;
        self.phoneLabel.text = model.phoneNumber;
        self.genderLabel.text = model.gender;
        self.imageV.image = [UIImage imageNamed:@"nvshen"];
    }
    
  3. 把系统的cell替换成自定义cell 完成

     CellModel *model=_dataArray[indexPath.row];
     static NSString *identifier = @"GirlCell";
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[MyTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier] autorelease];
        }
        // 在给cell赋值的同时,希望也给cell上的控件完成赋值
        cell.model = model;
    
        return cell;
    

混合使用cell

在 (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中判断model中的值来创建不同的cell。

这里写图片描述

另:创建ManTableViewCell

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

    // 显示数据
    CellModel *model=_dataArray[indexPath.row];
    // 根据model的值进行判断 显示不同的cell
    if ([model.gender isEqualToString:@"女"]) {
        // 创建女的
        static NSString *identifier = @"GirlCell";
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[MyTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier] autorelease];
        }
        // 在给cell赋值的同时,希望也给cell上的控件完成赋值
        cell.model = model;

        return cell;

    }else{
        // 创建男的
        static NSString *identifier = @"ManCell";
        ManTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[ManTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier] autorelease];
        }
        // 在给cell赋值的同时,希望也给cell上的控件完成赋值
        cell.model = model;
        return cell;
    }

cell自适应高度

步骤

自适应高度的label

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(40, 100, 300, 100)];
    label.backgroundColor = [UIColor greenColor];
    label.font = [UIFont systemFontOfSize:16];
    label.text = @"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈";
    // 计算字符串所占的高度
    // 参数size 宽度和你的label一边宽
    // 高度 填一个最大高度
    // CGFLOAT_MAX 最大的float数
    // 构建字体大小的字典  UIFont
    // NSFontAttributeName在系统中得属性的名字(key)
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16],NSFontAttributeName, nil];
    CGRect frame = [label.text boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
      // 更改label的高度
    CGRect temp = label.frame;
    temp.size.height = frame.size.height;
    label.frame = temp;
    label.numberOfLines = 0;
    [self.window addSubview:label];
    [label release];

举例

这里写图片描述

主要代码解释:

// 在自定义cell中创建一个类方法,使外部可以调用(类名调用)
// 计算字符串的高度
+ (CGFloat)cellHeightForModel:(NewsModel *)model
{
    // 创建字体大小的字典
    NSDictionary *fontDic = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
    CGRect textRect = [model.summary boundingRectWithSize:CGSizeMake(kLabelWidth, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:fontDic context:nil];
    return textRect.size.height;
}

// setModel方法:
- (void)setModel:(NewsModel *)model
{
    if (_model != model) {
        [_model release];
        _model = [model retain];
    }
    // 利用model中得点选状态,解决cell复用问题
    // 需要每次被复用的cell 再进行一次与状态对应的赋值
    if (model.isSelect == YES) {
        self.imageV.image = [UIImage imageNamed:@"select"];
    }else{
        self.imageV.image = [UIImage imageNamed:@"cancel"];
    }


    self.titleLabel.text = model.title;
    self.summaryLabel.text = model.summary;

    // 获取字符串的高度
    CGFloat summaryHeight = [MyTableViewCell cellHeightForModel:model];
    // 改变一下label的高度
  //  self.summaryLabel.height = summaryHeight;
    // 结构体赋值方法
    CGRect frame = self.summaryLabel.frame;
    frame.size.height = summaryHeight;
    self.summaryLabel.frame = frame;
}

判断cell的点选状态,改变图片

// cell点击的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取出被点击的cell
    MyTableViewCell *cell = (MyTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    // 更改cell上的图片

    // 取出点击cell对应的model
    NewsModel *model = _dataArray[indexPath.row];

    model.isSelect = !model.isSelect;
    if (model.isSelect == YES) {
        cell.imageV.image =[UIImage imageNamed:@"select"];

    }else{
        cell.imageV.image =[UIImage imageNamed:@"cancel"];

    }


}

设置cell高度:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 上边距 + titleLabel + 中间边距 + 动态高度 + 下边距
    NewsModel *model = _dataArray[indexPath.row];
    CGFloat labelHeight = [MyTableViewCell cellHeightForModel:model];
    CGFloat cellHeight = 60 + labelHeight;

    return cellHeight;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值