1

我有一种基于动态类型创建自动缩放字体的方法,如下所示:

extension UIFont {
    public static func getAutoScalingFont(_ fontName: String, _ textStyle: UIFont.TextStyle) -> UIFont {
        // getFontSize pulls from a map of UIFont.TextStyle and UIFont.Weight to determine the appropriate point size
        let size = getFontSize(forTextStyle: textStyle)
        guard let font = UIFont(name: fontName.rawValue, size: size) else { 
            return UIFont.systemFont(ofSize: size)
        }
        let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
        let traitCollection = UITraitCollection(preferredContentSizeCategory: UIApplication.shared.preferredContentSizeCategory)
        let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle, compatibleWith: traitCollection)
        return fontMetrics.scaledFont(for: font, maximumPointSize: fontDescriptor.pointSize)
    }
}

这似乎很好用;当我在手机设置中更改文本大小滑块值时,字体会根据需要进行缩放。

我现在正在尝试添加最小UIContentSizeCategory 的逻辑。也就是说,如果用户将他们的文本大小值设置为小于我指定的最小大小类别,则字体应该像他们选择了最小值一样缩放。

这是我的尝试:

extension UIFont {
    // This variable represents the minimum size category I want to support; that is, if the user
    // chooses a size category smaller than .large, fonts should be scaled to the .large size
    private static let minimumSupportedContentSize: UIContentSizeCategory = .large

    public static func getAutoScalingFont(_ fontName: String, _ textStyle: UIFont.TextStyle) -> UIFont {
        let size = getFontSize(forTextStyle: textStyle)
        guard let font = UIFont(name: fontName.rawValue, size: size) else { 
            return UIFont.systemFont(ofSize: size)
        }
        // I've extended UIContentSizeCategory to adhere to Comparable so this works fine
        let contentSize = max(UIApplication.shared.preferredContentSizeCategory, minimumSupportedContentSize)
        let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
        let traitCollection = UITraitCollection(preferredContentSizeCategory: contentSize)
        let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle, compatibleWith: traitCollection)
        return fontMetrics.scaledFont(for: font, maximumPointSize: fontDescriptor.pointSize)
    }
}

通过日志,我可以看出,正如预期的那样,contentSize我传递给 UITraitCollection 初始化程序的值永远不会小于.large. 但是,传递给该初始化程序的值似乎代表了最大内容大小类别。也就是说,如果我像这样初始化特征集合:

let traitCollection = UITraitCollection(preferredContentSizeCategory: .large)

字体将为所有小于的 UIContentSizeCategory 重新缩放,.large但不会为大于 的任何类别重新缩放.large

有谁知道如何完成设置最小UIContentSizeCategory?

4

0 回答 0