cell自適應高度字體
方式一:在自定義cell的自適應高度圖片
一、在自定義cell的.h文件中聲明兩個類方法string
//求一段文本的顯示高度it
+ (CGFloat)heightForString:(NSString *)string;io
//求cell的高度table
+ (CGFloat)cellHeightForStudent:(Student *)student;自適應
二、在自定義cell的.m文件中寫方法的實現方法
//求一段文本的顯示高度im
+ (CGFloat)heightForString:(NSString *)string {協議
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
CGRect rect = [string boundingRectWithSize:CGSizeMake(3 *kImageWidth, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
return rect.size.height;
}
//返回cell的高度
+ (CGFloat)cellHeightForStudent:(Student *)student {
CGFloat totalHeight = 65 + [GirlTableViewCell heightForString:student.introduce];
return totalHeight > 120 ? totalHeight : 120;
}
三、遵循協議- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath設定cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [MyTableViewCell cellHeightForStudent:student];
}
四、在自定義cell的LayoutSubViews方法中設定子視圖的高度
_introduceLabel.frame = CGRectMake(10, 65, 3 * imageWidth, [MyTableViewCell heightForString:self.student.introduce]);
方式二:系統cell的自適應高度
一、文本自適應高度,根據文本內容設定高度
NSString *str = @「dibibfnbdfbiehiehiorjogjteobjoebmtlrmnklgrou9q7924529854038510280ifopkwolvbnnbeijoejorjgesgfndbkndfbivjfi」 ;
// 獲取字體樣式屬性
NSDictionary *att = @{NSFontAttributeName:[UIFont
systemFontOfSize:17.0]};
// 根據字體樣式屬性獲取高度
CGRect rect = [str boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:nil];
[self.showLabel setFrame:CGRectMake(0, 0, 200, rect.size.height)];
二、圖片自適應高度,根據圖片寬度進行等比縮放
UIImage *aImage = [UIImage imageNamed:@"1.png"];
// 獲取圖片真實高度
CGFloat height = aImage.size.height;
CGFloat width = aImage.size.width;
// 縮放後寬度固定爲150
CGFloat scale = width / 150;
CGFloat realHeight = height / scale;
[self.myImageView setFrame:CGRectMake(0, 0, 200,realHeight)];