Search code examples
iosswiftaccessibilityios14dynamic-type-feature

maximumContentSizeCategory in iOS 14


In our recent project, we're trying to add Dynamic Text Sizing support. Our app is supporting iOS 14 and above.

In iOS 15, we can limit the text sizing using the property maximumContentSizeCategory and minimumContentSizeCategory.

label.maximumContentmSizeCategory = .accessibilityLarge

Question - What is the alternative of maximumContentSizeCategory and minimumContentSizeCategory in iOS 14?


Solution

  • Use UIApplication.shared.preferredContentSizeCategory to decide which preferredContentSizeCategory to use with UITraitCollection

    Example:

    func getPreferredFont(textStyle: UIFont.TextStyle, weight: UIFont.Weight? = nil) -> UIFont {
        let preferredContentSizeCategory: UIContentSizeCategory
        switch UIApplication.shared.preferredContentSizeCategory {
        case .extraSmall, .small, .medium:
            preferredContentSizeCategory = .large
        case .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge:
            preferredContentSizeCategory =  .accessibilityLarge
        default:
            preferredContentSizeCategory = UIApplication.shared.preferredContentSizeCategory
        }
        let traitCollection = UITraitCollection(preferredContentSizeCategory: preferredContentSizeCategory)
        let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle, compatibleWith: traitCollection)
        let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
        let font: UIFont
        if let weight = weight {
            font = UIFont.systemFont(ofSize: fontDescriptor.pointSize, weight: weight)
        } else {
            font = UIFont.systemFont(ofSize: fontDescriptor.pointSize)
        }
        return fontMetrics.scaledFont(for: font, maximumPointSize: fontDescriptor.pointSize, compatibleWith: traitCollection)
    }