How to use a custom font with dynamic text sizes in iOS7

前端 未结 12 2093
长情又很酷
长情又很酷 2020-11-29 14:41

In iOS7 there are new API\'s for getting a font that is automatically adjusted to the text size the user has set in their preferences.

It looks something like this to

12条回答
  •  孤独总比滥情好
    2020-11-29 15:08

    Similar to @bill-weinman's approach, I took the scales, and broke it out into a function that doesn't rely on a given font size of 16.

    /// The font scale for a given font size.
    ///
    /// - seealso: [Source](https://stackoverflow.com/a/33114525/3643020)
    ///
    /// - Parameter fontSize: The font size.
    /// - Returns: The font scale
    public func fontScale(for fontSize: CGFloat) -> CGFloat {
        switch UIApplication.shared.preferredContentSizeCategory {
        case UIContentSizeCategory.accessibilityExtraExtraExtraLarge:    return (fontSize + 8) / fontSize
        case UIContentSizeCategory.accessibilityExtraExtraLarge:         return (fontSize + 7) / fontSize
        case UIContentSizeCategory.accessibilityExtraLarge:              return (fontSize + 6) / fontSize
        case UIContentSizeCategory.accessibilityLarge:                   return (fontSize + 5) / fontSize
        case UIContentSizeCategory.accessibilityMedium:                  return (fontSize + 4) / fontSize
        case UIContentSizeCategory.extraExtraExtraLarge:                 return (fontSize + 3) / fontSize
        case UIContentSizeCategory.extraExtraLarge:                      return (fontSize + 2) / fontSize
        case UIContentSizeCategory.extraLarge:                           return (fontSize + 1) / fontSize
        case UIContentSizeCategory.large:                                return 1.0
        case UIContentSizeCategory.medium:                               return (fontSize - 1) / fontSize
        case UIContentSizeCategory.small:                                return (fontSize - 2) / fontSize
        case UIContentSizeCategory.extraSmall:                           return (fontSize - 3) / fontSize
        default:
            return 1.0
        }
    }
    

    It can then be used with custom fonts like this:

    /// Light font of specified size.
    ///
    /// - Parameter size: Font size.
    /// - Returns: Light font of specified size.
    func lightFont(ofSize size: CGFloat) -> UIFont {
        let scaledSize = size * fontScale(for: size)
    
        return UIFont(name: "HelveticaNeueLTStd-Lt", size: scaledSize)!
    }
    

提交回复
热议问题