Dav*_*e G 4 uilabel uifont ios swift
当人们询问如何设置粗体时,大多数人建议:
let boldFont = UIFont.boldSystemFont(ofSize: ___)
Run Code Online (Sandbox Code Playgroud)
但是,请看一下标准系统字体提供的所有字体权重:
所以我的问题是如何设置字体的粗细,半粗体或粗体?我知道的唯一方法是:
sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];
Run Code Online (Sandbox Code Playgroud)
但是,我仍然在问,因为这不是强类型的。其他大多数类的属性是通过从一组固定的选项中进行选择来设置的,不需要传递可能会打错的字符串。我想我可以设置自己的全局枚举...但是还有更好的主意吗?
我无法UIFontDescriptor使用字体粗细特征,但是还有另一种方法。
let font = UIFont.systemFont(ofSize: 20, weight: .light)
Run Code Online (Sandbox Code Playgroud)
替换.light为您要从UIFont.Weight中基本上与问题中显示的下拉列表匹配的任何值。
您可以使用此扩展程序。它将权重分配给 fontDescriptor 的权重键,并使用这个新描述符实例化您的字体。
extension UIFont {
func withWeight(_ weight: UIFont.Weight) -> UIFont {
let newDescriptor = fontDescriptor.addingAttributes([.traits: [
UIFontDescriptor.TraitKey.weight: weight]
])
return UIFont(descriptor: newDescriptor, size: pointSize)
}
}
Run Code Online (Sandbox Code Playgroud)
非常古老的线程,但有人可能对如何在 Swift 中做到这一点感兴趣。
UIFont.Weight定义所有选项:
你可以像这样简单地使用,例如:
label.font = UIFont.systemFont(ofSize: size, weight: .bold)
Run Code Online (Sandbox Code Playgroud)
或者如果您想保留以前的尺寸:
label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4170 次 |
| 最近记录: |