sizewithattributes没有返回正确的大小

问题描述:

我正在计算uitableview单元格中文本标签的高度。在看到sizewithfont已被ios 7弃用后,我实现了sizewithattributes,但返回值比它应该使标签对其包含的文本尺寸正确的方式要小得多。我也试过sizetofit方法也无济于事。sizewithattributes没有返回正确的大小

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

署名:

user/Elio.d有一个伟大的答案here.

我已经把它贴在下面他的回答的成绩单。如果它可以帮助你,请一定要在发送Elio.d的给予好评his original answer


成绩单:

那么你可以试试这个:

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]; 
+0

这工作,但只有当我设置自动布局来关闭在IB和当我做的标签都在uitableview单元格中我有他们在 – user2489946

+5

这个答案是从elio.d,不是你的。 http://stackoverflow.com/questions/19145078/ios-7-sizewithattributes-replacement-for-sizewithfontconstrainedtosize – Brave

+1

@Brave复制粘贴其他人的工作就像那么蹩脚。我已经对他进行了适当的归因编辑,希望能够推动更多Elio.d的发言 –