- (void)setLabelHeight:(UILabel *)label labelText:(NSString *)text font:(UIFont *)font {
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
paraStyle.alignment = NSTextAlignmentJustified;
NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@0.0f};
NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:text attributes:dic];
label.attributedText = attributeStr;
}
[self setLabelHeight:self.locationLab labelText:self.locationLab.text font:[UIFont systemFontOfSize:12]];
##### 需要自适应高度的label调用上边这方法即可
//返回cell高度
+ (CGFloat)getCellHeightWithString:(NSString *)string {
CGFloat height = [ScanInfoCell initWithSize:CGSizeMake(SCREEN_WIDTH - 30 - 58, CGFLOAT_MAX) string:string font:12].height + 51;
if (!string) {
height += 14.5;
}
return height;
}
//字符串转size
+ (CGSize)initWithSize:(CGSize)size string:(NSString *)string font:(NSInteger)font {
NSDictionary *attribute = @{NSFontAttributeName : [UIFont systemFontOfSize:font]};
CGSize sizes = [string boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
return sizes;
}
####在tableview代理方法中调用下边方法即可达到效果
//返回cell高度
+ (CGFloat)getCellHeightWithString:(NSString *)string;
如下:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//设置地址label自适应 cell高度随label高度变化
ScanInfo *scan = self.viewModel.scanHistoryArr[indexPath.section];
return [ScanInfoCell getCellHeightWithString:scan.deviceLocation];
}