我有一种基于动态类型创建自动缩放字体的方法,如下所示:
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)
}
}
这看起来效果很好;当我更改手机设置中的文本大小滑块值时,字体会根据需要进行缩放。
我现在正在尝试添加逻辑minimumUIContentSizeCategory。也就是说,如果用户将其文本大小值设置为小于我指定的最小大小类别,则字体应按比例缩放,就像他们选择了最小值一样。
这是我的尝试:
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
。但是,传递给该初始值设定项的值似乎代表一个maximum内容大小类别。也就是说,如果我像这样初始化特征集合:
let traitCollection = UITraitCollection(preferredContentSizeCategory: .large)
对于所有小于 UIContentSizeCategory 的字体,字体将重新缩放.large
但不会针对大于的任何类别重新缩放.large
.
有谁知道如何完成设置minimumUIContentSizeCategory?