IOS--UI Cell 自适应高度

来源:互联网 发布:java二次开发前景怎样 编辑:程序博客网 时间:2024/05/17 03:17

学习 NetWork 的时候遇到了 cell 的自适应高度问题 发现自己并不理解 网查很多资料 也是一知半解 结合笔记和老师介绍 不得不说 给我讲题这个老师真是自大的很
有不同的意见的朋友 可以留言 我这只是拙见
1.cell 的自适应高度 算是分两大部
① 你需要这一个返还 cell 高度的接口 并且还要在你所使用的. m 文件中返回 cell 里面信息结束之前写出

接口:#warning Cell 自适高度第一步//写一个接口,返回当前 cell 的行高  为什么是 Mode+(CGFloat)cellHight:(NewsMode *)newsMode;#warning cell 自适第三步//返回 cell 的高度 这个方法比 tableView:cellForRowAtIndexPath 提前执行-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return [NewsTableViewCell cellHight:self            .dataSource[indexPath.row]];}//重用 cell- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsCell" forIndexPath:indexPath];    //    NewsMode *newS =self.dataSource[indexPath.row];    cell.news = newS;    return cell;}

② cell 的返还高度 实际上就是计算你的文本高度,

//计算 summary 文本高度 根据字符串算 所以是 nsstring+(CGFloat)summaryHeight:(NSString *)summary{    //    1.文本渲染只需要矩形大小, 按要求宽度要和文本大小的宽(label)是一样的 必须是固定值(你之前设的数组) ,高度设置为多少都可以(0或10000)最终文本高度的大小是根据文本内容计算得到的高度    CGSize contextSize =CGSizeMake(280, 0)    ;    NSLog(@"%@", summary);    //    计算设置的文本大小 必须和你之前上面这顶的一样    NSDictionary * attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:17.0]};    CGRect summayRect=[summary boundingRectWithSize:contextSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil];    return summayRect.size.height;}

注: label 是行数的 如果你使用 StoryBoard 搭建 设定 lines 为0 就好 如果是代码 需要再加个方法 让 lines 返回值为0;

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];    if (self) {        [self p_setUp];    }return self;}-(void)p_setUp{//布局,在这里将titleLabel 和 summaryLabel 的 frame 设为固定的值,当需要改变的时候我们在改变,在这个方法中需要将设置清楚两个 label 的字号的大小,以及在summaryLabel 的 text 中设置换行  这一步可以省略 在 sb 里面设定    self.summaryLabel.numberOfLines = 0;}

总结:
这样看看 cell 的自适高度 理解上很容易 但是你要记住的话 还需要多加练习 我总结之后再想想 还是个不会啊%>_<%

0 0
原创粉丝点击