为什么 systemFontOfSize 和 SFPro-Regular 字体创建的文本大小在 iOS13 中不相等?

Why the size of text created by font of systemFontOfSize and SFPro-Regular aren't equal in iOS13?

根据apple's development guidance.

得知iOS13中的系统默认字体是SF Pro

我在游荡[UIFont systemFontOfSize:18]可能会被[UIFont fontWithName:@"SFPro-Regular" size:18]重播

但是我发现这两种字体的文字大小不一样:

大小由boundingRectWithSize计算如下:

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:content attributes:@{NSFontAttributeName: font}];
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

然后我尝试了其他字体,如SF MonoNew YorkSanFrancisco,结果都与[UIFont systemFontOfSize:18]

不同

所以,问题是:

  1. 系统默认的字体是什么?
  2. 如果SF Pro确实是系统默认字体,为什么大小不一样?

iOS 版本之间一直存在 - 并且可能永远存在 - 细微差异。

使用此代码,例如:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let v = UILabel()
    v.text = "test"
    view.addSubview(v)
    v.font = UIFont.systemFont(ofSize: 18)
    v.frame = CGRect(x: 40, y: 100, width: 200, height: 60)

}

我运行它在iOS12.1iOS 13.3(不同的物理设备)然后使用Debug View Hierarchy检查UI元素,我发现:

  • iOS 12: .SFUIText 18.00pt
  • iOS 13: .SFUI-Regular 18.00pt

如果你真的需要像素精度,你几乎肯定需要为每个 UI 元素.

我不是说“不要使用 Apple 的 SF 字体”......我只是说不要尝试混合搭配 systemFontOfSize 加载应用程序fontWithName.