[TwistedFate]UITableViewCell自定义-02

UITableViewCell自定义

cell分区的行高自适应

采用类方法,是为了在返回cell的行高时调用

//  计算字符串的高度
+ (CGFloat)cellHeightForModel:(NewsModel *)model{

    //  创建字体大小的字典
    //  字面量初始化
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:16]};

CGRect textRect = [model.summary boundingRectWithSize:CGSizeMake(kScreenWidth - kMargin * 2, 6666) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];

return textRect.size.height;

}

返回cell行高

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    //  计算高度
    CGFloat labelHeight = [NewsTableViewCell cellHeightForModel:self.newsArray[indexPath.row]];

    //  上边距 toplabel + 中间距离 + 动态label高度 + 下边距

    return 20 + 40 + 20 + labelHeight + 40;
}

解决cell的复用性问题

划出屏幕的cell在被重用时,重新赋值了

在model类里添加状态属性

//  标识选中的状态
@property (nonatomic, assign) BOOL isSelected;

在数据处理过程中为模型对象添加状态属性值

//  数据处理
- (void)dataProcess{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsData" ofType:@"plist"];

    self.dataDic = [NSMutableDictionary dictionaryWithContentsOfFile:path];

   NSString *key = @"news";

    NSArray *dataArray = self.dataDic[key];

    self.newsArray = [NSMutableArray array];

    for (NSDictionary *dic in dataArray) {

        NewsModel *model = [[NewsModel alloc] init];


        [model setValuesForKeysWithDictionary:dic];

        //  给点击状态加一个初值
        model.isSelected = NO;

        [self.newsArray addObject:model];

        [model release];

    }

}

在模型属性的set方法里根据不同的状态赋不同的值

- (void)setModel:(NewsModel *)model{

    if (_model != model) {

        [_model release];

        _model = [model retain];

    }

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

    //  利用model中的点选状态解决cell复用的问题
    //  需要背刺被复用的cell 再进行一次与状态对应对应的赋值
    if (model.isSelected == YES) {

        self.imageV.image = [UIImage imageNamed:@"select"];

    }else{

        self.imageV.image = [UIImage imageNamed:@"cancel"];

    }


    //  计算字符串的高度
    CGFloat summaryHeight = [NewsTableViewCell cellHeightForModel:model];

    //  改变一下label的高度
    self.summaryLabel.height = summaryHeight;

    //  多行显示
    self.summaryLabel.numberOfLines = 0;
    // 设置字体大小

    self.summaryLabel.font = [UIFont systemFontOfSize:16];

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值