UIFontExtension.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. //
  5. import UIKit
  6. extension UIFont {
  7. static func monospacedPreferredFont(forTextStyle style: TextStyle) -> UIFont {
  8. let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
  9. let font = UIFont.monospacedSystemFont(ofSize: fontDescriptor.pointSize, weight: .regular)
  10. return UIFontMetrics(forTextStyle: style).scaledFont(for: font)
  11. }
  12. // See: https://stackoverflow.com/a/62687023
  13. static func preferredFont(for style: TextStyle, weight: Weight, italic: Bool) -> UIFont {
  14. // Get the style's default pointSize
  15. let traits = UITraitCollection(preferredContentSizeCategory: .large)
  16. let desc = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style, compatibleWith: traits)
  17. // Get the font at the default size and preferred weight
  18. var font = UIFont.systemFont(ofSize: desc.pointSize, weight: weight)
  19. if italic == true {
  20. font = font.with([.traitItalic])
  21. }
  22. // Setup the font to be auto-scalable
  23. let metrics = UIFontMetrics(forTextStyle: style)
  24. return metrics.scaledFont(for: font)
  25. }
  26. @objc
  27. static func preferredFont(for style: TextStyle, weight: Weight) -> UIFont {
  28. return preferredFont(for: style, weight: weight, italic: false)
  29. }
  30. private func with(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont {
  31. guard let descriptor = fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits).union(fontDescriptor.symbolicTraits)) else {
  32. return self
  33. }
  34. return UIFont(descriptor: descriptor, size: 0)
  35. }
  36. }