在iOS 7中,sizeWithFont:现已弃用.我现在如何将UIFont对象传递给替换方法sizeWithAttributes:?
在iOS7中,sizeWithFont不推荐使用,因此我正在使用boundingRectWithSize(返回CGRect值).我的代码:
UIFont *fontText = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
// you can use your font.
CGSize maximumLabelSize = CGSizeMake(310, 9999);
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:fontText}
context:nil];
expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);
Run Code Online (Sandbox Code Playgroud)
在textRect,我的尺寸大于我maximumLabelSize,尺寸与使用时不同sizeWithFont.我该如何解决这个问题?
我正在创建一个显示带有一些文本的窗口的类,一个"不再显示"复选框和一个按钮.为了可重用,类会根据需要调整窗口大小以适合文本.
但是,在计算中有一些细微的不精确 - 如果我不向宽度添加5个像素,则某些字符串会被截断.(简单地删除了最后一个字.)
这就是我所拥有的:
// NSTextField *textLabel;
// NSString *text;
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject: [textLabel font] forKey: NSFontAttributeName];
NSRect textFrame = [text boundingRectWithSize:NSMakeSize(textLabel.frame.size.width, (unsigned int)-1)
options:(NSStringDrawingDisableScreenFontSubstitution | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:stringAttributes];
textFrame.size.width += 5;
Run Code Online (Sandbox Code Playgroud)
我暂时将标签的背景颜色设置为黄色以使调试更容易,并且它显然扩展到几乎适合最后一个单词.该测试字符串上有4个像素的额外值.
请注意,没有添加这些像素,并非所有字符串都会失败
我关心的原因有两个:
1)我想知道为什么它有点错误,更重要的是
2)我想通过改变计算后的宽度,理论上包装可以改变并且不使用最后一行,在文本下面创建额外的空白区域.