问题描述
如果我有自己的一组大小和权重不同的UIFont
,例如:
let customFont03 = UIFont.systemFont(ofSize: 40, weight: .thin)
我如何支持Dynamic Type
,同时仍将我的自定义大小和权重保留为默认标准,并根据用户选择辅助功能大小的方式进行缩放?
我不确定preferredFont(forTextStyle:)
是我想要的,因为它只接受UIFont.TextStyle
,而我不想将customFont03
锁定为.body
或.headline
...
推荐答案
动态系统字体,指定样式、粗细和斜体
在SWIFT 5中。
我不敢相信苹果没有提供一种更干净的方法来获得具有特定粗细的动态字体。以下是我的综合解决方案,希望对您有所帮助!
extension UIFont {
static func preferredFont(for style: TextStyle, weight: Weight, italic: Bool = false) -> UIFont {
// Get the style's default pointSize
let traits = UITraitCollection(preferredContentSizeCategory: .large)
let desc = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style, compatibleWith: traits)
// Get the font at the default size and preferred weight
var font = UIFont.systemFont(ofSize: desc.pointSize, weight: weight)
if italic == true {
font = font.with([.traitItalic])
}
// Setup the font to be auto-scalable
let metrics = UIFontMetrics(forTextStyle: style)
return metrics.scaledFont(for: font)
}
private func with(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont {
guard let descriptor = fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits).union(fontDescriptor.symbolicTraits)) else {
return self
}
return UIFont(descriptor: descriptor, size: 0)
}
}
您可以这样使用它:
UIFont.preferredFont(for: .largeTitle, weight: .regular)
UIFont.preferredFont(for: .headline, weight: .semibold, italic: true)