默认的UIFont大小和粗细,但也支持首选字体文本样式

发布时间:2022-08-15 / 作者:清心寡欲
本文介绍了默认的UIFont大小和粗细,但也支持首选字体文本样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有自己的一组大小和权重不同的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)

这篇关于默认的UIFont大小和粗细,但也支持首选字体文本样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Default UIFont size and weight but also support preferredFontForTextStyle


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。