OGeek|极客世界-中国程序员成长平台

标题: ios - 默认 UIFont 大小和重量,但也支持 preferredFontForTextStyle [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:50
标题: ios - 默认 UIFont 大小和重量,但也支持 preferredFontForTextStyle

如果我有自己的一组具有不同大小和重量的 UIFont,例如:

let customFont03 = UIFont.systemFont(ofSize: 40, weight: .thin)

如何在支持 Dynamic Type 的同时仍保留我的自定义尺寸和重量作为默认标准并根据用户选择无障碍尺寸的方式进行缩放?

我不确定 preferredFont(forTextStyle 是我想要的,因为它只接受 UIFont.TextStyle 而我不想锁定 customFont03 作为 .body.headline 等...



Best Answer-推荐答案


动态系统字体,指定样式、粗细和斜体

在 Swift 5 中。

我不敢相信 Apple 没有提供一种更简洁的方法来获得具有特定权重的动态字体。这是我的综合解决方案,希望对您有所帮助!

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)

关于ios - 默认 UIFont 大小和重量,但也支持 preferredFontForTextStyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356530/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4