iOS tableViewCell自適應高度

cell上面放圖片和文字,可以使用cell自身cell自身的屬性cell.imageView和cell.textLabel,也可以自己給cell上添加imageView和label。

1.圖片自適應高度:根據圖片的寬高比例,通過數學比例運算得出圖片應該顯示的高度,來設置相框的高度

(1)計算圖片等比例高度

- (CGFloat)imageScaleHeightWithImage:(NSString *)name

{

UIImage *aImage = [UIImage imageNamed:name];

CGFloat width = aImage.size.width;

CGFloat height = aImage.size.height;

return height / width * [UIScreen mainScreen].bounds.size.width;

}

(2)設置cell上的高度,調用上面方法

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

return [self imageScaleHeightWithImage:@"圖片名"];

}

(3)效果圖如下:

2.對給定文字來限制他的應該的高度,用這個高度來設置Label的范圍

// 計算label的高度? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -(CGFloat)labelHeightWithText:(NSString *)text font:(UIFont *)font

{

NSDictionary *dic = @{NSFontAttributeName : font};

CGRect rect = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

return rect.size.height;

}

(2)設置cell上的高度,調用上面方法。 注意設置cell.textLabel多行顯示。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

cell.textLabel.text = @“自定義文本”; //例如:@“剛剛,就剛剛。我們廠里那個16歲的女孩子囂張的找我說。要我退出我的婚姻,我跟我老公不合適,說我人老珠黃。她說他愛我老公,感覺我老公也喜歡他,我兒子她會視如己出,要我乖乖的立馬走人,不要讓她愛的人為難,說完走了,我他媽的氣笑了,24歲的我人老珠黃?我最先想到的事竟然是先發糗百”

cell.textLabel.numberOfLines = 0; ?

return cell;

}

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

?return [self labelHeightWithText:self.string font:[UIFont systemFontOfSize:19]];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容