计算UITableViewCell高度以适合string
我有一个NSMutableArray
,可能包含几百个不同的string。 每个string都是用户定义的,可以有任何长度,但不超过平均段落。
我需要找出每个string可以采用多less行。 所以,我可以计算每个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:
- (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
。