[英]Calculate UITableViewCell height to fit string
I have a NSMutableArray
, which could contain several hundreds of different strings. 我有一个
NSMutableArray
,它可以包含数百个不同的字符串。 Each string is user defined and could have any length, yet no more than an average paragraph. 每个字符串都是用户定义的,并且可以具有任何长度,但不能超过平均段落。
I need to find out how many lines each string could take. 我需要找出每个字符串可以使用多少行。 So, I could calculate the required height for a every
UITableviewCell
. 因此,我可以为每个
UITableviewCell
计算所需的高度。
Use the following code to calculate and to set the height for cell: 使用以下代码来计算和设置单元格的高度:
- (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;
}
I personally use a convenience method which I then send a message to in tableView:heightForRowAtIndexPath:
我个人使用便利的方法,然后在
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);
}
And of course, I set the numberOfLines
property of my UILabel
to 0
in UITableViewCell
. 当然,我在
UITableViewCell
中将UILabel
的numberOfLines
属性设置为0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.