如何计算UILabel行中有多less个字符?

我想用单元格的dynamic高度制作一个UITableview 。 在每个单元格中,我正在显示不同文本的消息。 现在我想要我的表格单元格根据消息的文本,并且我单元格上的单元格应显示文本。 我正在使我的表格单元格可以容纳一行字符的数量的基础上灵活。 但是这是问题。 不同的字母需要不同的空间。 所以,我无法计算一行中可以有多less个字母。 对此有何build议?

尝试这个 :

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{CGSize size; if (SYSTEM_VERSION_LESS_THAN(@"7.0")) { // code here for iOS 5.0,6.0 and so on CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17]]; size = fontSize; } else { // code here for iOS 7.0 NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica Neue" size:19], NSFontAttributeName, nil]; CGRect fontSizeFor7 = [text boundingRectWithSize:CGSizeMake(571, 500) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil]; size = fontSizeFor7.size; }return size.height +30 ; } 

检查我的答案

计算UITableViewCell高度以适合string

在这里你必须根据文本计算标签的高度,然后设置单元格的高度。

你可以使用它dynamic地计算高度和宽度。

我希望这会帮助你

你不想统计你的文本有多less个字符,只需要使用下面的数字来计算高度:

 h = [NSString stringWithFormat:@"%f", [post.text boundingRectWithSize:CGSizeMake(298.0f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont fontWithName:@"Helvetica Neue" size:14.0] forKey: NSFontAttributeName] context:nil].size.height] 

使用你的宽度为298和你的字体/字体大小。

请我下面的答案

 UILabel *lbl = [[UILabel alloc] init]; lbl.text = @"abcd"; NSLog(@"count %lu",(unsigned long)[lbl.text length]); 
 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString * yourCellStr = @"The string you want to apply to your cell at this index path"; CGSize maxLblSize = CGSizeMake(320, 200); CGSize expectedLblSize = [yourCellStr sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:maxLblSize lineBreakeMode:NSLineBreakByWordWrapping]; return expectedLblSize.height; }