IOS 7中sizeWithFont已被弃用

3

我似乎无法正确地使用 boundingRecWithSize 替换被弃用的 sizeWithFont。我浏览了所有答案,整晚都在尝试解决这个问题。我真的需要比我聪明得多的人的帮助。这是我正在尝试修改的代码。任何帮助都将不胜感激。

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

1
可能是在iOS 7中弃用的sizeWithFont:的替代方法?的重复问题。 - Daij-Djan
3个回答

9
您需要使用sizeWithAttributes属性。
CGSize mysize = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f]}];

您也可以将其设置为已创建的字体大小,以便在多次使用该大小时减少重新编码的工作:
CGSize mysize = [string sizeWithAttributes:@{NSFontAttributeName: label1.font}];

我不认为你可以在此属性中使用constrainedToSize。它必须单独设置在CGRect上。


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

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

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