Scale text on iOS
Apps should scale text to the size specified by users in the system settings. This is especially important for visually impaired users because they might not be able to read the text otherwise.
On iOS, you can use Dynamic Font Size to scale text. By using this function, the font size is adjusted to the preferences of the user. If you're using your own font, you can use the scaledFont
method from UIFontMetrics
to calculate the font size.
import UIKit
extension UIFont {
static func font(name: String, size: CGFloat, style: TextStyle) -> UIFont {
guard let font = UIFont(name: name, size: size) else {
fatalError("Font \(name) does not exist")
}
return UIFontMetrics(forTextStyle: style).scaledFont(for: font)
}
static func openSans(weight: UIFont.Weight, size: CGFloat, style: TextStyle) -> UIFont {
if UIAccessibility.isBoldTextEnabled {
return font(name: "OpenSans-Bold", size: size, style: style)
}
switch weight {
case .regular:
return font(name: "OpenSans-Regular", size: size, style: style)
case .semibold:
return font(name: "OpenSans-SemiBold", size: size, style: style)
case .bold:
return font(name: "OpenSans-Bold", size: size, style: style)
default:
fatalError("Font weight \(weight) is not supported")
}
}
}