Is it possible to use dynamic type sizes with a custom font in SwiftUI?

后端 未结 3 1857
傲寒
傲寒 2020-12-31 11:04

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

3条回答
  •  囚心锁ツ
    2020-12-31 11:48

    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.

提交回复
热议问题