iosswiftswiftuiuifont

System Font with custom size for text style


Aim:

I would like to know how to use a system font in my SwiftUI app with a custom size that supports dynamic size (that changes when the user changes the text size on the device, font size changes dynamically).

Problem:

I can use the standard .body, .title etc for system fonts, however I want to use a custom size which is slightly different however still want to make sure it works with dynamic types

My Failed Attempt:

//Font size doesn't change when the user changes his preferred text size on the device
Text("hello")
    .font(.system(size: 14, weight: .bold, design: .default))

Note:

I am targeting iOS 15, I am looking for something on the lines of the following for system font:

static func custom(_ name: String, size: CGFloat, relativeTo textStyle: Font.TextStyle) -> Font

Questions:


Solution

  • Following Font function helps achieve custom font size relative to TextStyle:

    static func custom(
        _ name: String,
        size: CGFloat,
        relativeTo textStyle: Font.TextStyle
    ) -> Font