[英]Calculate UITableViewCell height to fit string
我有一个NSMutableArray
,它可以包含数百个不同的字符串。 每个字符串都是用户定义的,并且可以具有任何长度,但不能超过平均段落。
我需要找出每个字符串可以使用多少行。 因此,我可以为每个UITableviewCell
计算所需的高度。
使用以下代码来计算和设置单元格的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Define `veryverySmallTitleFont`
// Define `descLabel`
NSString *ourText = @"Your string data from array";
UIFont *font = [UIFont fontWithName:@"Verdana" size:veryverySmallTitleFont];
font = [font fontWithSize:veryverySmallTitleFont];
CGSize constraintSize = CGSizeMake(descLabel.frame.size.width, 1000);
CGSize labelSize = [ourText sizeWithFont:font
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height;
}
我个人使用便利的方法,然后在tableView:heightForRowAtIndexPath:
中将消息发送到tableView:heightForRowAtIndexPath:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self cellHeightForRowAtIndexPath:indexPath];
}
- (CGFloat)cellHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellString = <YOUR MODEL OBJECT>;
NSDictionary *attributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:16.0f] };
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
initWithString:cellString
attributes:attributes];
CGFloat width = self.tableView.frame.size.width - 32.0f;
CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin context:nil];
// Add some extra padding to the height
CGFloat height = frame.size.height + 16.0f;
return ceil(height);
}
当然,我在UITableViewCell
中将UILabel
的numberOfLines
属性设置为0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.