3

I cannot seem to replace the deprecated sizeWithFont with boundingRecWithSize correctly. I scoured through all the answers and stayed up all night trying to fix this.I really need help from someone way smarter than I. Here is the code I am trying to modify. Any help would be appreciated.

CGSize sizeForText = [faqItem.answer sizeWithFont:[UIFont boldSystemFontOfSize:14]
   constrainedToSize:CGSizeMake(self.tblView.bounds.size.width - padding, MAXFLOAT)
   lineBreakMode:NSLineBreakByWordWrapping];

[sectionInfo insertObject:[NSNumber numberWithFloat:roundf(sizeForText.height + 5)]
  inRowHeightsAtIndex:0];
4

3 回答 3

9

您需要使用 sizeWithAttributes 属性。

CGSize mysize = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f]}];

如果您多次使用该大小,您还可以将其设置为已创建的字体大小以减少重新编码:

CGSize mysize = [string sizeWithAttributes:@{NSFontAttributeName: label1.font}];

我不相信您可以将此属性与 constrainedToSize 一起使用。它必须在 CGRect 上单独设置。

于 2015-01-07T19:32:13.530 回答
3

我为你写了一个示例,希望对你有所帮助。

NSString *text = @"    // Do any additional setup after loading the view, typically from a nib.";
CGRect rect = CGRectZero;
NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};

rect = [text boundingRectWithSize:CGSizeMake(100,9999)
                          options:(NSStringDrawingUsesLineFragmentOrigin)
                       attributes:attrDict
                          context:Nil];

UILabel *lbl = [[UILabel alloc] init];
lbl.text = text;
rect.origin = CGPointMake(50, 200);
lbl.frame = rect;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
[self.view addSubview:lbl];
lbl.backgroundColor = [UIColor lightGrayColor];
于 2015-01-13T09:26:08.087 回答
-3

在苹果文档中:

sizeWithFont:如果要在单行上使用指定的字体呈现字符串,则返回字符串的大小。(在 iOS 7.0 中已弃用。改用 sizeWithAttributes:。)

  • (CGSize)sizeWithFont:(UIFont *)font 参数 font 用于计算字符串大小的字体。返回值 结果字符串边界框的宽度和高度。这些值可能会四舍五入到最接近的整数。

所以你可以使用 sizeWithAttributes:像这样:

 CGSize sizeForText = [faqItem.answer sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]}
                       constrainedToSize:CGSizeMake(self.tblView.bounds.size.width - padding, MAXFLOAT) 
                           lineBreakMode:NSLineBreakByWordWrapping];

[sectionInfo insertObject:[NSNumber numberWithFloat:roundf(sizeForText.height + 5)] 
      inRowHeightsAtIndex:0];
于 2013-10-25T19:39:18.237 回答