I\'m playing around with SwiftUI, and want to use a custom UI font for my project. However, I don\'t want to lose the dynamic type resizing that comes with the built-in font
I stumbled upon a nice way to achieve this also via ViewModifier
. I borrowed the base modifier from this Hacking With Swift's article on Dynamic Type and Custom Fonts. Here's the result:
import SwiftUI
@available(iOS 13, macCatalyst 13, tvOS 13, watchOS 6, *)
struct CustomFont: ViewModifier {
@Environment(\.sizeCategory) var sizeCategory
var name: String
var style: UIFont.TextStyle
var weight: Font.Weight = .regular
func body(content: Content) -> some View {
return content.font(Font.custom(
name,
size: UIFont.preferredFont(forTextStyle: style).pointSize)
.weight(weight))
}
}
@available(iOS 13, macCatalyst 13, tvOS 13, watchOS 6, *)
extension View {
func customFont(
name: String,
style: UIFont.TextStyle,
weight: Font.Weight = .regular) -> some View {
return self.modifier(CustomFont(name: name, style: style, weight: weight))
}
}
And usage:
Text("Hello World!")
.customFont(name: "Georgia", style: .headline, weight: .bold)
This way you can stick to bundled Text Styles without needing to provide sizes explicitly. Should you want to do so, the font
modifier already allow us to, and the scaling could be handled through one of the alternative approaches given to this question.
Also, please note that because the styling is applied within a ViewModifier
conformant struct
, which in turn responds to changes to the environment's sizeCategory
, the views will reflect changes to the accessibility settings right upon switching back to your app; so there's no need to restart it.