2

我有以下代码:

float height = [string sizeWithFont:[UIFont systemFontOfSize:kFontSize] constrainedToSize:CGSizeMake(widthOfTextView, 999999.0f) lineBreakMode:NSLineBreakByWordWrapping].height + verticalPadding;

但是,每当我运行我的应用程序并收到警告,告诉我这已被弃用。我应该使用什么以及如何将它与我当前的代码一起使用?

谢谢!

4

4 回答 4

2

sizeWithFont:ConstrainedToSize:lineBreakMode 自 iOS 7 起已弃用,因此我也一直在寻找替代品。到目前为止,这似乎是我找到的最佳答案:

https://stackoverflow.com/a/18746573/1275947

于 2013-09-12T13:04:18.607 回答
2

这被 [string boundingRectWithSize:options:attributes:context] 取代。“技巧”是创建一个包含您之前使用的字体和换行模式的属性字典。在您的情况下,应该是:

// Create a paragraph style with the desired line break mode
NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

// Create the attributes dictionary with the font and paragraph style
NSDictionary *attributes = @{
                               NSFontAttributeName:detailTextFont,
                               NSParagraphStyleAttributeName:paragraphStyle
                           };

// Call boundingRectWithSize:options:attributes:context for the string 
CGRect textRect = [string boundingRectWithSize:CGSizeMake(widthOfTextView, 999999.0f)
                                       options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:attributes
                                       context:nil];

float height = textRect.size.height;

如果您不使用段落样式,您将获得默认的 NSLineBreakByWordWrapping。

于 2014-11-12T19:16:13.060 回答
1

您实际上不需要那么远离最近不推荐使用的代码。正如它所说,有一个更好的替代品,但你应该注意只有 iOS7 可以使用它。市场通常要求我们至少向后定位一个主要版本......此外,一些 API 来来去去,您可以等待下一个主要版本,看看时间是否证明更新您的代码库的好处。

于 2013-10-02T12:47:49.177 回答
0

它在文档中告诉您。

它说该方法已被弃用,然后告诉您应该使用什么来代替它。

你应该使用:boundingRectWithSize:options:attributes:context:

于 2013-10-02T20:17:51.130 回答