在iOS中, 很多情况下不知道视图的高度是多少, 这时候就需要自适应高度了.
第一步 写方法 方法写在自定义视图中
+(CGFloat)suitHeight:(NSString *)text font:(UIFont *)font width:(CGFloat)width{
CGSize size = CGSizeMake(width, MAXFLOAT);
NSDictionary *style = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGRect result = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:style context:nil];
return result.size.height;
}
第二步 计算返回Cell高度 一般写在当前视图控制器中
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//对象赋值 Contact *contact = [self.arraySort objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
CGFloat result = [FirstTableViewCell suitHeight:contact.hobby font[UIFont systemFontOfSize:17]width:self.width.frame.size.width];
CGFloat singleHeight = [FirstTableViewCell suitHeight:@“s” font:[UIFont systemFontOfSize:17] width:self.width.frame.size.width];
return 250 + result - singleHeight;
}
第三步 计算具体高度, 赋值 计算之后的height即自适应的高度
CGFolat height = [FirstTableViewCell suitHeight:self.hobbyLabel.text font:self.hobbyLabel.font width:self.nameLabel.frame.size.width];