iOS Swift how to detect Dynamic Type Sizes with customer Font

1.6k Views Asked by At

I have already finished dynamic type customer font set in my App through this article:

https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-dynamic-type-with-a-custom-font

but i got new requirements from designer:

enter image description here

as you can see we have xSmall/Small/Medium/Large/xLarge/xxLarge/xxxLarge 7 totally font sizes in Apple HIG.

designer give the following rules:

xSmall -> same with app current default size

Small -> same with app current default size

Medium -> same with app current default size

Large -> Default size

xLarge -> Default size + 1pt

xxLarge -> Default size + 2pt

xxxLarge -> Default size + 3pt

my question is how to detect App system font set to small or xLarge so that i can give some compute value? how to approach the new requirements?

3

There are 3 best solutions below

0
matt On BEST ANSWER

Watch for the trait collection to change and read the preferredContentSizeCategory. If it has changed, mess with the interface as desired.

0
Noor On

You can use following snippet for custom font with DynamicType in SwiftUI

Text("Large Title")
        .font(
            .custom(
                "Custom Font",
                size: 34,
                relativeTo: .largeTitle

            )
        )
0
Harrison Cho On

I'll provide a solution using the default size of .body as an example. If you implement it in the way shown in the code below, you can create a font size that dynamically changes relative to .body. If you have specific font size information, you can simply enter the font sizes for each case.

extension Font {
    static func customBody(for sizeCategory: ContentSizeCategory) -> Font {
        let defaultBodySize = UIFont.preferredFont(forTextStyle: .body).pointSize

        switch sizeCategory {
        case .extraSmall, .small, .medium:
            return .system(size: defaultBodySize)
        case .large:
            return .system(size: defaultBodySize)
        case .extraLarge:
            return .system(size: defaultBodySize + 1)
        case .extraExtraLarge:
            return .system(size: defaultBodySize + 2)
        case .extraExtraExtraLarge:
            return .system(size: defaultBodySize + 3)
        default:
            return .body
        }
    }
}
struct ContentView: View {
    @Environment(\.sizeCategory) var sizeCategory

    var body: some View {
        VStack{
            Text("Default body size")
                .font(.body)
            Text("Custom body size")
                .font(.customBody(for: sizeCategory))
        }
    }
}