如何计算UILabel行中可以包含的字符数



我想为单元格制作一个具有动态高度的UITableview。在每个单元格中,我都会显示一条不同文本的消息。现在我希望我的表格单元格符合消息的文本,并且单元格上的标签应该显示文本。我正在根据一行中可以容纳的字符数使我的表格单元格变得灵活。但问题来了。不同的字母占用不同的空间。所以,我无法计算一行中可以包含多少个字母。对此有什么建议吗???

试试这个:

-(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 ;
    }

您不想计算文本的字符数,只需使用计算高度即可

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和您的字体/fontsize。

检查我的答案

计算UITableViewCell高度以适合字符串

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

使用此选项可以动态计算高度和宽度。

我希望它能帮助你

-(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;
}

请我在下面回答

UILabel *lbl = [[UILabel alloc] init];
 lbl.text = @"abcd";
 NSLog(@"count %lu",(unsigned long)[lbl.text length]);

最新更新