您的位置:首页 > 其它

32.CELL⾃适应⾼度

2015-11-24 21:53 246 查看

之前我们使⽤的cell⼀直都是同样的⾼度,或者某⾏固定⾼度。

实际开发中经常要让cell根据Model中⽂本的⻓短动态的更改⾼度

方法1.取出被点击的Cell

MyTableViewCell cell = (MyTableViewCell )[tableView cellForRowAtIndexPath:indexPath];

步骤1.获取字符串的高度

步骤2. 改变一下label的高度

步骤3.改变每行的高度

在自定义cell.m文件中

重写了setter方法

- (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.isSelect == YES) {

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

}else{

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

}

步骤1.获取字符串的高度

CGFloat summaryHeight = [MyTableViewCell cellHeightForModel:model];

步骤2. 改变一下label的高度

self.summaryLabel.height = summaryHeight;

}

计算字符串的高度(用类方法方便外面调取)

+ (CGFloat)cellHeightForModel:(NewsModel *)model

{

创建字体大小的字典

NSDictionary *fontDic = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};

计算字符串高度

CGRect textRect = [model.summary boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];

return textRect.size.height;

}

在根视图中

设置每行有多高

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

{

取出对应的model

NewsModel *model = self.dataArray[indexPath.row];

计算高度

CGFloat summary = [MyTableViewCell cellHeightForModel:model];

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

步骤3.改变每行的高度

return summary + 20 + 40 + 20 + 20;

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: