繁体   English   中英

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

[英]sizewithAttributes not returning the correct height for uilabels

我正在尝试使用sizewithattributes方法在uitableview中计算uilabel的正确高度。 但是它返回的高度远低于应有的高度,标签文本被切除,并且从textwithattributes返回的高度输出到控制台,即使对于整段文本,其高度也大约为20-40。 我在方法的属性部分中将字体大小和字体设置为与uilabel相同,并且将换行模式设置为uilabel的自动换行。 提前致谢

代码:`

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

您的问题符合要求:

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

您将文本宽度指定为100000 pt,但我不知道content字符串包含多少个字符,但是如果行长10000 pt,我相信您可以轻松地在一两行显示它。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM