SwiftUI Custom Font Size inside Picker using SegmentedPickerStyle

Viewed 2031

I am attempting to customize the font size of the two tags inside the Picker. I am using the SegmentedPickerStyle and I would like the Picker font size to match Text size of the other titles/strings that I am using on my form. The other fonts are using .font(.headline)

var body: some View {
NavigationView {
    ScrollView {
        VStack(alignment: .leading){
            Group {
                Picker("", selection: $form.nameType) {
                    Text("First/Last name \(form.nameType == 0 ? "*" : "")").tag(0)
                    Text("Company name \(form.nameType == 1 ? "*" : "")").tag(1)
                    }
                    .pickerStyle(SegmentedPickerStyle())    
                }
            }
        }
    }
}
2 Answers

You can customize the font of your segment controllers adding this:

init() {
        UISegmentedControl.appearance().setTitleTextAttributes(
            [
                .font: UIFont.systemFont(ofSize: 18),
            ], for: .normal)
    }

To expand on @Ludyem's correct answer, if in addition you'd like your SwiftUI SegmentedPickerStyle to support Dynamic Type fonts, then this should do the trick:

let font = UIFont.preferredFont(forTextStyle: .footnote) // regular weight
UISegmentedControl.appearance().setTitleTextAttributes([.font: UIFont.systemFont(ofSize: font.pointSize, weight: .medium)], for: .normal) // medium weight

   

The default font for a UISegmentedControl appears to be systemFont(ofSize: 13) - which correspond to UIFont.TextStyle.footnote - but medium weight. So the above gets the scaled (13pt) footnote font, and then adjust the weight to match.

Related