How to fix collapsing list when adding navigationBarItems to Picker

Viewed 88

I'm trying to include a "+" or "New User" button in a SwiftUI Picker list of current users to allow user to Add a new user to the list. When I add .navigationBarItems, the list of current users collapses into a single form item.

import SwiftUI

struct SuperHeroView: View {
    private var users = [User(id: UUID(), name: "Batman", username: "brucewayne"),
                 User(id: UUID(), name: "Spider Man", username: "peterparker"),
                 User(id: UUID(), name: "Superman", username: "clarkkent")]
    @State private var selectedSuperHero = UUID()
    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Picker(selection: $selectedSuperHero, label: Text("Super Hero")) {
                        ForEach(users) { user in
                            Text(user.name)
                        }
                    }
                }
            }
        }
    }
}

original

Changing to:

import SwiftUI

struct SuperHeroView: View {
    private var users = [User(id: UUID(), name: "Batman", username: "brucewayne"),
                 User(id: UUID(), name: "Spider Man", username: "peterparker"),
                 User(id: UUID(), name: "Superman", username: "clarkkent")]
    @State private var selectedSuperHero = UUID()
    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Picker(selection: $selectedSuperHero, label: Text("Super Hero")) {
                        ForEach(users) { user in
                            Text(user.name)
                        }.navigationBarItems(trailing: Text("New User"))
                    }
                }
            }
        }
    }
}

using navigationBarItems

I've tried moving the placement of the .navigationBarItems code, to no avail.

How can I add the navigationBarItems without affecting the structure of the Picker Items?

0 Answers
Related