ios - 默认 UIFont 大小和重量,但也支持 preferredFontForTextStyle
<p><p>如果我有自己的一组具有不同大小和重量的 <code>UIFont</code>,例如:</p>
<pre><code>let customFont03 = UIFont.systemFont(ofSize: 40, weight: .thin)
</code></pre>
<p>如何在支持 <code>Dynamic Type</code> 的同时仍保留我的自定义尺寸和重量作为默认标准并根据用户选择无障碍尺寸的方式进行缩放?</p>
<p>我不确定 <code>preferredFont(forTextStyle:)</code> 是我想要的,因为它只接受 <code>UIFont.TextStyle</code> 而我不想锁定 <code>customFont03</code> 作为 <code>.body</code> 或 <code>.headline</code> 等...</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><h3>动态系统字体,指定样式、粗细和斜体</h3>
<p>在 Swift 5 中。</p>
<p>我不敢相信 Apple 没有提供一种更简洁的方法来获得具有特定权重的动态字体。这是我的综合解决方案,希望对您有所帮助!</p>
<pre><code>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)
}
}
</code></pre>
<p>你可以这样使用它:</p>
<pre><code> UIFont.preferredFont(for: .largeTitle, weight: .regular)
UIFont.preferredFont(for: .headline, weight: .semibold, italic: true)
</code></pre></p>
<p style="font-size: 20px;">关于ios - 默认 UIFont 大小和重量,但也支持 preferredFontForTextStyle,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/53356530/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/53356530/
</a>
</p>
页:
[1]