UIFont - 如何获取系统细字体

106

UIFont有获取常规字体(systemFontOfSize)或加粗字体(boldSystemFontOfSize)的方法,但如何获取在Storyboard中可用的"细系统字体"呢?

将"system-thin"传递给UIFont构造函数是无效的,该构造函数仅适用于非系统字体。

4个回答

278
你可以使用系统字体的细体(thin weight):
UIFont.systemFont(ofSize: 34, weight: UIFontWeightThin)

旧金山字体可用的字重列表:

UIFontWeightUltraLight
UIFontWeightThin
UIFontWeightLight
UIFontWeightRegular
UIFontWeightMedium
UIFontWeightSemibold
UIFontWeightBold
UIFontWeightHeavy
UIFontWeightBlack

旧版的San Francisco字重

iOS 11之后,UIFontWeight*被改名为UIFont.Weight.*。更多信息可在此处获取:https://developer.apple.com/documentation/uikit/uifont.weight


10
仅适用于 iOS 8.2 及以上版本,谢谢。 - Husam

32

iOS 8.2起,您现在可以使用UIFont.systemFontOfSize(_ fontSize: CGFloat, weight weight: CGFloat):

UIFont.systemFontOfSize(19, weight: UIFontWeightLight)

iOS SDK为权重提供了常量:

UIFontWeightUltraLight
UIFontWeightThin
UIFontWeightLight
UIFontWeightRegular
UIFontWeightMedium
UIFontWeightSemibold
UIFontWeightBold
UIFontWeightHeavy

当您想要使用系统字体时,与其基于字体名称创建字体,不如使用系统字体更好,因为在iOS中,Apple可以更改其系统字体(例如,在iOS 7中他们所做的Helvetica Neue和现在iOS 9中的San Francisco)。

因此,我建议将所需字体的TTF文件包含在内,将该ttf文件用作自定义字体并在应用程序中使用自定义字体。

这就是我不喜欢苹果的特殊原因。永远不要听从Apple的话。总是去做我们想要的。Apple会不断更改每个操作系统的默认字体。


7

如果您想保持相同的字体大小,只是改变字体粗细,则可以使用目标元素的字体大小。例如:

demoLabel.font = UIFont.systemFont(ofSize: demoLabel.font.pointSize, weight: UIFontWeightThin)

使用此方法,您可以保持默认标签字体大小,只需更改字重。

iOS 11起,UIFontWeightThin被重命名为UIFont.Weight.thin。更多信息,请访问https://developer.apple.com/documentation/uikit/uifont.weight


3

Swift 4.2 / Swift 5.0

 label.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.thin)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接