sizeWithAttributes 为我提供了不同的 CGSize 宽度和高度

sizeWithAttributes gets me a different CGSize width and height

提问人:feldeOne 提问时间:1/10/2019 更新时间:1/11/2019 访问量:495

问:

在 iOS 中,7 已弃用。建议的替换方法是
但是当我将方法从 更改为
时,我会得到不同的值。
sizeWithFont:sizeWithAttributes:sizeWithFont:sizeWithAttributes:

这是我的代码:

CGSize temp = [opt.option sizeWithFont:[UIFont fontWithName:fontFamily size:[self randomFontSize]]];
NSLog(@"Old SizeWithFont value %f x %f",temp.height, temp.width);

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:fontFamily size:[self randomFontSize]]};
temp = [opt.option sizeWithAttributes: attributes];
NSLog(@"New SizeWithAttribute has value %f x %f",temp.height, temp.width);

输出为:

linespacing 16.33, fontsize 16.00
Old SizeWithFont value 18.000000 x 47.000000
New SizeWithAttribute has value 17.875000 x 46.250000

我做错了什么吗?我

iOS的 Objective-C Cocoa iOS7

评论

1赞 Mats 1/10/2019
根据文档,这似乎是预期的行为。这些函数在舍入返回值的方式上有所不同。
0赞 danh 1/11/2019
请注意,更清晰的实验将使用文字常量来表示字体名称、字体大小、正在测量的字符串等。

答:

3赞 danh 1/11/2019 #1

属性文本方法描述暗示了行为差异(我添加的粗体)......

此方法返回小数大小;使用返回的 size 到 size 视图中,必须使用 CEIL 函数。

它还指出,整数大小应该用(换句话说,四舍五入)来计算。这样做可以使您的实验按预期工作...ceil()

NSLog(@"New SizeWithAttribute has value %f x %f",ceil(temp.height), ceil(temp.width));

评论

0赞 feldeOne 1/11/2019
谢谢 danh,我想你的意思是我必须对 NSLog 进行舍入(@“New SizeWithAttribute has value %f x %f”,ceil(temp.height), ceil(temp.width));