Search code examples
iosswiftuipickerswiftui-picker

SwiftUI picker title?


I'm trying to use the Picker for a simple selection. Currently I'm using the .inline navigation bar for showing the titles. (here's where i got the example https://www.hackingwithswift.com/quick-start/swiftui/pickers-in-forms)

struct ContentView: View {
    var strengths = ["Mild", "Medium", "Mature"]

    @State private var selectedStrength = 0
    
    var body: some View {
        NavigationView {
            Form {
                Picker(selection: $selectedStrength, label: Text("Strength")) {
                    ForEach(0 ..< strengths.count) {
                        Text(self.strengths[$0])
                    }
                }
            }.navigationBarTitle("Parent Title", displayMode: .inline)
        }
    }
}

So my issue is that when I go into the picker, there is no title? Screenshot 1

When I try to set the inline title on the Picker, or ForEach or even the Texts inside the foreach, the Parent Title gets overridden...

Is there a nice way of fixing this problem or should i just go ahead and make my own picker (any good simple pickers our there)?


Solution

  • This is what I ended up doing (got the idea from Change Navigation Title of Picker in SwiftUI thanks to Claus Jørgensen):

    struct ContentView: View {
        var strengths = ["Mild", "Medium", "Mature"]
    
        @State private var selectedStrength = 0
    
        var body: some View {
            NavigationView {
                Form {
                    Picker(selection: $selectedStrength, label: Text("Strength")) {
                        ForEach(0 ..< strengths.count) {
                            Text(self.strengths[$0])
                        }.navigationBarTitle("Strength", displayMode: .inline)
                    }.navigationBarTitle("Parent Title", displayMode: .inline)
                }
            }
        }
    }