Here is a reformatting of Luke Howard's solution to reduce the amount of text
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let style: UIFont.TextStyle
switch font {
case .largeTitle: style = .largeTitle
case .title: style = .title1
case .title2: style = .title2
case .title3: style = .title3
case .headline: style = .headline
case .subheadline: style = .subheadline
case .callout: style = .callout
case .caption: style = .caption1
case .caption2: style = .caption2
case .footnote: style = .footnote
case .body: fallthrough
default: style = .body
}
return UIFont.preferredFont(forTextStyle: style)
}
}
From Swift 5.9, you can use the switch statement to return a value and have an even less cluttered look:
extension UIFont {
class func preferredFont(from font: Font) -> UIFont {
let style: UIFont.TextStyle =
switch font {
case .largeTitle: .largeTitle
case .title: .title1
case .title2: .title2
case .title3: .title3
case .headline: .headline
case .subheadline: .subheadline
case .callout: .callout
case .caption: .caption1
case .caption2: .caption2
case .footnote: .footnote
default: /*.body */ .body
}
return UIFont.preferredFont(forTextStyle: style)
}
}
SwiftUI.Font
is aView
, whereUITextView.font
is a UIFontSwiftUI.Font
is just a plainStruct
conforms toEquatable
andHashable
, not aView
: developer.apple.com/documentation/swiftui/fontleading()
one.