1.自定义cell的.h文件里
/*声明一个类方法 ,用来计算高度 */
+ (CGFloat)heightWithText: (NSString *)text;
2.自定义.m文件里面实现
+ (CGFloat)heightWithText: (NSString *)text
{
CGRect rect = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width , 0) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:17]} context:nil];
return rect.size.height;
}
3.方法调用
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
(Cell1为自定义cell)
return [Cell1 heightWithText:[self.arr objectAtIndex:indexPath.row]];
}
二.图片自定义高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *image = [UIImage imageNamed:[self.arr objectAtIndex:indexPath.row]];
return 375 * image.size.height / image.size.width;
}