Skip to content

Instantly share code, notes, and snippets.

@hishma
Last active May 5, 2020 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishma/502ebbacf3ed879d1a0c5d6c6c3ddb2c to your computer and use it in GitHub Desktop.
Save hishma/502ebbacf3ed879d1a0c5d6c6c3ddb2c to your computer and use it in GitHub Desktop.
import UIKit
extension UIFont {
/// Returns an instance of the font associated with the text style, specified design, and scaled appropriately for the user's selected content size category.
/// - Parameters:
/// - style: The text style for which to return a font. See UIFont.TextStyle for recognized values.
/// - weight: The weight of the font, specified as a font weight constant. For a list of possible values, see "Font Weights” in UIFontDescriptor. Avoid passing an arbitrary floating-point number for weight, because a font might not include a variant for every weight.
/// - fontDesign: The new system font design.
/// - Returns: A font object of the specified style, weight, and design.
@available(iOS 13.0, *)
static func preferredFont(forTextStyle style: UIFont.TextStyle, weight: UIFont.Weight = .regular, fontDesign: UIFontDescriptor.SystemDesign = .default) -> UIFont {
let metrics = UIFontMetrics(forTextStyle: style)
let fontSize = UIFont.preferredFont(forTextStyle: style).pointSize
var font = UIFont.systemFont(ofSize: fontSize, weight: weight)
if let descriptor = UIFont.systemFont(ofSize: fontSize, weight: weight).fontDescriptor.withDesign(fontDesign) {
font = UIFont(descriptor: descriptor, size: fontSize)
}
return metrics.scaledFont(for: font)
}
}
@hishma
Copy link
Author

hishma commented May 5, 2020

Example usage:

let font =  UIFont.preferredFont(forTextStyle: .headline, weight: .semibold, fontDesign: .rounded)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment