iOS自动计算tableViewCell的高度(Xib约束,代码控制)

代码1:
别的就不写了,简单记录一下就OK

import <Foundation/Foundation.h>

import "ITTBaseModelObject.h"

// ITTBaseModelObject 这个类是Runtime进行Model赋值的,自己写,自己继承就好了.
注意俩点
1:Model属性需要和后台返回的一一对应
2:后台返回"<null>" Runtime转完后就成了字符串,用字符串判断
([[NSString stringWithFormat:@"%@",url] isEqualToString:@"<null>"])
Model类
@interface NoteModel : ITTBaseModelObject
@property (nonatomic)CGFloat cellHeight;
@end

import "NoteModel.h"

@implementation KGCNoteModel

  • (CGFloat)cellHeight
    {
    //第一个textH是label文字长度去定义高度
    CGFloat textH = [self getContactHeight:self.content with:kScreenWidth-40];
    CGFloat ImageViewheght=10;
    _cellHeight = 90 + textH + ImageViewheght;
    return _cellHeight;
    }

-(float)getContactHeight:(NSString*)contact with:(CGFloat)DeviceWidth
{
NSDictionary *attrs=@{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
CGSize maxSize=CGSizeMake(DeviceWidth,MAXFLOAT);
CGSize size=[contact boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
return size.height;
}
//需要子类重写,自己处理

  • (NSDictionary *)attributeMapDictionary{
    return nil;
    }

//控制器进行设置高度就OK了,别的没什么写的了,cell可以用xib也可以写代码进行初始化cell的属性。

  • (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    NoteModel *model = self.NodaArrayData[indexPath.row];
    return model.cellHeight;
    }

自动布局Xib:
label.text中间文字设置距离上下左右约束,文字需要自动布局拉伸的,
所以不要添加约束去设置label的高和宽。
有图片的话添加约束进行对图片进行高和宽约束。
其余的控件添加好了就OK了。
然后代码如何写那,一句话就搞定。
两句代码实现tableView先走heightForCell后走cellForRow:

//tableView预设高度,苹果自动适配的.
self.NoteTableView.estimatedRowHeight = 100;
self.NoteTableView.rowHeight = UITableViewAutomaticDimension;

//下面的代理方法就不用写了(重点:不需要写)

  • (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    return 0;
    }
    //下面是tableViewCell.m 其余的什么都不需要写
    //很简单的,自动布局
    import "NoteTableViewCell.h"
    @implementation NoteTableViewCell
  • (void)awakeFromNib {
    [super awakeFromNib];
    self.headView.layer.cornerRadius=20; //头像圆
    self.headView.layer.masksToBounds=YES;//
    self.contentLabel.numberOfLines = 0;//label多行
    }
    @end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容