限制支持的 Dynamic Type 字体大小 [英] Limit supported Dynamic Type font sizes

查看:27
本文介绍了限制支持的 Dynamic Type 字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想支持 Dynamic Type 但仅限于一定的限制,类似于 Settings.app 中标准 UITableViewCell 可以增长到 UIContentSizeCategoryAccessibilityExtraExtraLarge但不是更大.

I want to support Dynamic Type but only to a certain limit, similar to the Settings.app where standard UITableViewCells can grow up to UIContentSizeCategoryAccessibilityExtraExtraLarge but not larger.

是否有一种简单的方法可以使用标准的 UITableViewCell 样式来完成此操作?

Is there an easy way to accomplish this with standard UITableViewCell styles?

推荐答案

我在 UIFont 上使用自定义类别来获取具有限制的首选字体,就像这样

I'm using a custom category on UIFont to get a preferred font with a limit, like this

extension UIFont {

  static func preferredFont(withTextStyle textStyle: UIFont.TextStyle, maxSize: CGFloat) -> UIFont {
    // Get the descriptor
    let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)

    // Return a font with the minimum size
    return UIFont(descriptor: fontDescriptor, size: min(fontDescriptor.pointSize, maxSize))
  }

}

对象

@implementation UIFont (preferredFontWithSizeLimit)

+ (UIFont *)preferredFontWithTextStyle:(UIFontTextStyle)style maxSize:(CGFloat)maxSize {
    // Get the descriptor
    UIFontDescriptor *fontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle: style];

    // Return a font with the minimum size
    return [UIFont fontWithDescriptor: fontDescriptor size: MIN(fontDescriptor.pointSize, maxSize)];
}

@end

要根据样式对限制进行硬编码,您可以添加如下内容(我将每种样式的当前系统默认值放在注释中)

To hard-code limits based on the style, you could add something like this (I put the current system default for each style in comments)

+ (UIFont *)limitedPreferredFontForTextStyle:(UIFontTextStyle)style {
    // Create a table of size limits once
    static NSDictionary *sizeLimitByStyle;
    static dispatch_once_t once_token;
    dispatch_once(&once_token, ^{
        sizeLimitByStyle = @{
            UIFontTextStyleTitle1: @56, // default 28
            UIFontTextStyleTitle2: @44, // default 22
            UIFontTextStyleTitle3: @40, // default 20
            UIFontTextStyleHeadline: @34, // default 17
            UIFontTextStyleSubheadline: @30, // default 15
            UIFontTextStyleBody: @34, // default 17
            UIFontTextStyleCallout: @32, // default 16
            UIFontTextStyleFootnote: @26, // default 13
            UIFontTextStyleCaption1: @24, // default 12
            UIFontTextStyleCaption2: @22, // default 11
        };
    });
    
    // Look up the size limit
    CGFloat maxSize = INFINITY;
    NSNumber *limit = sizeLimitByStyle[style];
    if (limit) {
        maxSize = limit.doubleValue;
    }
    // Return the font
    return [UIFont preferredFontWithTextStyle: style maxSize: maxSize];
}

这篇关于限制支持的 Dynamic Type 字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆