在 iOS 7 中替换已弃用的 sizeWithFont: 丢失

Lost with the replacement for deprecated sizeWithFont: in iOS 7

我收到一条警告,提示 sizeWithFont: 已弃用,我已尝试将其替换为 sizeWithAttributes: 但我尝试的所有方法均无效。

代码应该告诉我 UILabel 的预期大小,cCell 是 IB 的单元格和标签。

感谢您的帮助。

CGSize maximumLabelSize = CGSizeMake(210, FLT_MAX);

expectedLabelSize = [labelText sizeWithFont:cCell.lblHotelResponse.font constrainedToSize:maximumLabelSize lineBreakMode:cCell.lblHotelResponse.lineBreakMode];

您需要改用 sizeWithAttributes:

NSDictionary *attributeDict = @{NSFontAttributeName:cCell.lblHotelResponse.font};
CGSize expectedLabelSize    = [labelText sizeWithAttributes:attributeDict];

另一种方式是:

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:labelText attributes:@{NSFontAttributeName: cCell.lblHotelResponse.font}];
CGRect rect                          = [attributedString boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
CGSize labelSize                     = rect.size;

参考文献:

  1. sizeWithAttributes:
  2. boundingRectWithSize:options:attributes: