问题描述
我有以下代码:
float height = [string sizeWithFont:[UIFont systemFontOfSize:kFontSize] constrainedToSize:CGSizeMake(widthOfTextView, 999999.0f) lineBreakMode:NSLineBreakByWordWrapping].height + verticalPadding;
但是,每当我运行我的应用程序并收到警告,告诉我这是不赞成的。我应该使用什么以及如何将其与当前代码一起使用?
However, whenever I run my application and get a warning telling me that this is deprecated. What should I use and how would I use it with my current code?
谢谢!
推荐答案
这被[string boundingRectWithSize:options:attributes:context]取代。 技巧是创建一个属性字典,其中包含您以前使用的字体和换行模式。在您的情况下,应该是:
This is replaced by [string boundingRectWithSize:options:attributes:context]. The "trick" is to create an attributes dictionary that contains the font and line-break mode you were previously using. In your case, that should be:
// 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。
If you leave off the paragraph style, you will get the default of NSLineBreakByWordWrapping.
这篇关于sizeWithFont:constrainedToSize:不推荐使用lineBreakMode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!