sizewithAttributes没有为uilabels返回正确的高度

时间:2013-12-24 17:40:18

标签: ios iphone objective-c uitableview uilabel

我正在尝试使用sizewithattributes方法在uitableview中计算uilabels的正确高度。但它返回的高度远低于它应该的高度,标签文本被截断并输出从textwithattributes返回到控制台的高度,即使对于完整的文本段也显示大约20-40的高度。我已经将字体大小和字体设置为与方法的属性部分中的uilabel相同,并且我将断行模式设置为uilabel的wordwrap。在此先感谢

代码:`

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(  NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSDictionary *message =  self.messages[indexPath.row];
    NSLog(@"%lu", (long)indexPath.row);
    UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:20000];
    UILabel *messageContent = (UILabel *)[cell.contentView viewWithTag:10000];
    UIImageView *image = (UIImageView *)[cell.contentView viewWithTag:30000];
    UIButton *replyButton = (UIButton *)[cell.contentView viewWithTag:40000];
    replyButton.tag = indexPath.row;
    messageContent.text = [message objectForKey:@"messageContent"];
    NSString *content = [message objectForKey:@"messageContent"];
    NSLog(@"Message: %@", content);

    NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:17.0f]};
    // NSString class method: boundingRectWithSize:options:attributes:context is
    // available only on ios7.0 sdk.
    CGRect rect = [content boundingRectWithSize:CGSizeMake(10000, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];

    CGFloat height = ceilf(rect.size.height);
    CGFloat width  = ceilf(rect.size.width);
    messageContent.frame = CGRectMake(40, 126, width, height);


    NSLog(@"Height:%f", messageContent.frame.size.height);
    NSLog(@"y: %f", messageContent.frame.origin.y);
    NSLog(@"estimated height: %f", height);




    nameLabel.text = [message objectForKey:@"senderName"];

    UIImage *senderPic = self.senderPictures[indexPath.row];
    image.image = senderPic;
    image.layer.cornerRadius = 27.0;
    image.layer.masksToBounds = YES;





    return cell;
}
`

1 个答案:

答案 0 :(得分:1)

你的问题符合:

//[content boundingRectWithSize:CGSizeMake(10000, MAXFLOAT)

你指定了100000 pt作为文字的宽度,我不知道你的content字符串包含多少个字符,但我相信如果你的行是10000 pt,你可以很容易地用一两行显示它长。

更好的方法是将文本添加到标签的读取大小,并根据需要更改标签框架:

CGSize labelSize = [self.messageContent.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:self.messageContent.font.pointSize]}];