关于TableViewCell高度自适应问题的整理

styzxg 8年前

来自: http://www.cnblogs.com/huketianxia/p/5174943.html

TableViewCell高度自适应在网上有很多资料,我只想找出最最最简单的一种方法。

首先梳理一下思路。说到TableViewCell我们第一个想到的问题或许就是cell的复用问题。

1.  [self.tableView registerClass:[Cell class] forCellReuseIdentifier:str]; 注册之后可以在cell代理函数里调用

Cell *cell = [tableView dequeueReusableCellWithIdentifier:str forIndexPath:indexPath]; 方法去对cell进行设置,操作,无需再进行复用处理。

2. 没有进行register注册的需要先判断复用队列里有没有cell

1 Cell *cell = [tableView dequeueReusableCellWithIdentifier:str ];  2   3    if (!cell) {  4   5     cell = [[Cell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:str];  6   7    }

3.在 cellForRowAtIndexPath 函数里尽量不要去做添加控件的操作。因为,在if函数内添加,会出现数据重叠问题;而在if外面添加,会出现复用问题,黑乎乎一大片。如果确实需要,可以考虑自定义cell方法。分为纯代码和xib两种方式,纯代码方式建立的是Class类,而xib方式创建的是nib类。

cell高度自适应

1.如果我们想要在cell里面新建lable并且使其自适应高度,那么只能新建Class类(其实是我没找到可以用的nib解决方法)。初始化的时候添加控件,设置或者不设置其frame都可以,因为我们在下面会进行重新设置其frame。否则容易在断行方面出问题

 1 - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{   2        3     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];   4     if (self) {   5         _lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, maiSrc.width, 44)];   6            7         [self addSubview:_lable];   8            9         _imgv = [[UIImageView alloc]init];  10           11         [self addSubview:_imgv];  12           13     }  14     return self;  15 }

2.在cellForRowAtIndexPath方法里不能直接对Cell对象进行赋值,那么我们可以建立对象方法来进行设置。当然,记得在.h文件里声明这个对象方法。

 1 #import "Cell.h"   2    3 static CGFloat heightForCell ;   4 static CGFloat widthForCell ;   5    6 @implementation Cell   7    8 -(void)setHeightForLable:(NSString *)str fontForLable:(CGFloat)font CGSize:(CGSize)constraintSize{   9   10     //文字高度计算方法  11     CGFloat height = [[MineJN defaultMineJN] autoLayouHeightForLable:str fontSize:font constrainSize:CGSizeMake(maiSrc.width - widthForCell, CGFLOAT_MAX)];  12       13     heightForCell = heightForCell > height ? heightForCell : height;  14       15     self.lable.text = str;  16       17     self.lable.numberOfLines = 0;  18       19      self.lable.frame = CGRectMake(self.lable.frame.origin.x, self.lable.frame.origin.y, maiSrc.width - widthForCell, heightForCell);  20       21     //获取自身高度   然后将计算出来的高度赋值给他  22     CGRect frame = [self frame];  23       24     frame.size.height = heightForCell;  25       26     self.frame = frame;  27 }

3.文字高度计算方法是我工具类里的方法

 1 -(CGFloat)autoLayouHeightForLable:(NSString *)lableText fontSize:(CGFloat)fontSize constrainSize:(CGSize)maxSize{   2        3     CGSize constraintSize;   4        5     //对比最大约束maxSize与CGSizeZero是否相等,如果是的话给他赋一个初值。以无限高为最大高度,以屏幕宽-30为宽度。如果不相等可以直接沿用   6     if (CGSizeEqualToSize(maxSize, CGSizeZero)) {   7            8         constraintSize = CGSizeMake(maiSrc.width, CGFLOAT_MAX);   9     }else{  10         constraintSize = maxSize;  11     }  12       13       14     //计算方式   记得一般情况要有Origin  15     NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin;  16     /*  17      *字符串计算方式,NSStringDrawingUsesLineFragmentOrigin是以每行组成的矩形为单位计算整个文本的尺寸  18      *UsesFontLeading则以字体间的行距(leading,行距:从一行文字的底部到另一行文字底部的间距。)来计算。  19      *如果为NSStringDrawingTruncatesLastVisibleLine那么计算文本尺寸时将以每个字或字形为单位来计算。  20      *如果为NSStringDrawingUsesDeviceMetric,那么计算文本尺寸时将以每个字或字形为单位来计算。  21      */  22       23     //设置字符串字体号,字体颜色  24     NSDictionary *dic = [NSDictionary dictionaryWithObjects:@[[UIFont systemFontOfSize:fontSize],[UIColor blueColor]] forKeys:@[NSFontAttributeName,NSForegroundColorAttributeName]];  25       26     //iOS7以后用这个方法来计算lable自定义高度  27     CGRect stringRect = [lableText boundingRectWithSize:constraintSize options:options attributes:dic context:nil];  28       29     return stringRect.size.height;  30 }

4.写完cell的对象方法,并且其中lable的各种属性以及赋值情况都设置完成,那就可以到cellForRowAtIndexPath方法里去调用了

 1 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {   2        3        4     Cell *cell = [tableView dequeueReusableCellWithIdentifier:str];   5        6     //获取数据源   7     Info *io = _dataArr[indexPath.row];   8        9     if (!cell) {  10           11         cell = [[Cell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:str];  12   13     }  14       15     [cell setHeightForLable:io.intro fontForLable:18 CGSize:CGSizeMake(maiSrc.width, CGFLOAT_MAX)];  16       17     return cell;  18 }

完了。这份代码说的比较简单,只是给出了一个思路,具体怎么实现,还需要你自己去动脑子思考,纯粹的拿来主义很无聊,不管你在多久之后才看到这篇文章,都希望你能在遇到问题,看别人文章的时候进行认真思考。