【问题标题】:sizeWithAttributes gets me a different CGSize width and heightsizeWithAttributes 让我获得不同的 CGSize 宽度和高度
【发布时间】:2019-06-05 11:56:12
【问题描述】:

在 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】:

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

此方法返回小数大小;使用返回的大小来调整大小 视图,您必须使用将其值提高到最接近的更高整数 ceil 函数。

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

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

【讨论】:

  • 谢谢 danh,我想你肯定是说我要四舍五入 NSLog(@"New SizeWithAttribute has value %fx %f",ceil(temp.height), ceil(temp.width));
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 2017-04-11
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
相关资源
最近更新 更多