sizewithattributes不能返回正确的大小

9

我正在尝试计算uitableview单元格中文本标签的高度。在看到ios 7中已经弃用sizewithfont后,我实现了sizewithattributes,但返回值比标签正确大小所需的要小得多。我还尝试了sizetofit方法,但也没有成功。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSDictionary *message =  self.messages[indexPath.row];

    UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1];
    UILabel *messageContent = (UILabel *)[cell.contentView viewWithTag:3];
    UIImageView *image = (UIImageView *)[cell.contentView viewWithTag:2];
    messageContent.text = [message objectForKey:@"messageContent"];
    NSString *content = [message objectForKey:@"messageContent"];
    NSLog(@"Message: %@", content);

    CGSize textSize = [content sizeWithAttributes:@{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:17.0]}];
    messageContent.font = [UIFont fontWithName:@"HelveticaNue-Light" size:17.0];
    CGRect messageFrame = messageContent.frame;
    messageFrame.size = textSize;
    messageContent.frame = messageFrame;


    nameLabel.text = [message objectForKey:@"senderName"];
    NSString *senderPicture = [message objectForKey:@"senderPicture"];
    UIImage* myImage = [UIImage imageWithData:
                    [NSData dataWithContentsOfURL:
                     [NSURL URLWithString: senderPicture]]];

    image.image = myImage;
    image.layer.cornerRadius = 27.0;
    image.layer.masksToBounds = YES;

    //Configure the cell...

    return cell;
  }
1个回答

9

归属:

user/Elio.d这里给出了一个很棒的答案。

我附上了他的答案转录。如果它对你有帮助,请确保去Elio.d原始答案上投一票。


转录:

好的,你可以尝试这个:

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

这个可以运行,但只有我在IB上关闭自动布局时才有效,而当我这样做时,表格视图单元格中的标签会错位。 - user2489946
5
这个答案来自elio.d,不是我的。https://dev59.com/JmIk5IYBdhLWcg3wkvBn - Brave
3
@Brave 这样复制粘贴别人的工作是非常无聊的行为。我已经为他编辑了适当的归属,希望这会给 Elio.d 带来更多的赞同。 - Albert Renshaw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接