sizewithattributes没有返回正确的大小

use*_*946 8 cocoa-touch objective-c uilabel sizewithfont ios

我想计算uitableview单元格中文本标签的高度.在看到sizewithfont被ios 7弃用之后,我实现了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;
  }
Run Code Online (Sandbox Code Playgroud)

Pra*_*inh 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];
Run Code Online (Sandbox Code Playgroud)

  • 这个答案来自elio.d,而不是你的.http://stackoverflow.com/questions/19145078/ios-7-sizewithattributes-replacement-for-sizewithfontconstrainedtosize (5认同)
  • @Brave 像这样复制粘贴别人的作品真是太蹩脚了。我已经为他编辑了正确的归属,希望这能为 Elio.d 带来更多的支持 (3认同)