需求背景:
類似朋友圈酥诽,有文字鞍泉,有圖片,文字的高度不定肮帐,cell的高度需要根據(jù)文字和圖片的數(shù)量進(jìn)行計(jì)算
我們知道tableview的delegate里面有兩個(gè)方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
使用MVC的方式咖驮,對(duì)這個(gè)問題進(jìn)行解析,M---model训枢, V---cell, 所謂的提前計(jì)算高度就是在model里將高度計(jì)算好托修,拋一個(gè)property出去,在heightForRow方法里取model的時(shí)候恒界,直接把height取出來使用睦刃。
以下是手碼的偽代碼,直接在這里打的哈十酣,可能不能運(yùn)行
@interface model : NSObject
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, copy) NSArray *picArray;
@property (nonatomic, copy) NSString *content;
-
(void)caculateForCellHeight;
@end@implementation model - (void)caculateForCellHeight { self.cellHeight = 0; if (self.picArray.count > 0) { self.cellHeight += onePicHeight * picRow; } if (self.content.lenght > 0) { UILabel label= [[UILabel alloc] initWithFrame:[在cell里承接centent的cell一樣的尺寸涩拙,高可以是任意,寬要和cell里的一樣]]; label.numberOfLine = 0; // 屬性設(shè)置耸采,如font行數(shù)等等 CGSize contentSize = [label sizeThatFits:CGSizeMake(label.width, MAXFLOAT)]; self.cellHeight +=contentSize.height; } } @end
controller里給model賦值的時(shí)候兴泥,就直接調(diào)用一次caculateForCellHeight方法,在heightForRow里就可以直接根據(jù)index取出對(duì)應(yīng)的model虾宇,從model里取出cellHeight,這樣tableview滑動(dòng)就會(huì)降低卡的程度搓彻,如果每次都計(jì)算的話,會(huì)使界面很卡,而且可能會(huì)出現(xiàn)跳動(dòng)