Search code examples
arraysswiftswiftuipickerswiftui-picker

How do I make a continuously updated picker in swift ui?


i am currently working on a app in swift ui. In the App is the function to add groups, and on the Mainscreen you can pick one of these groups. My problem is, that the one option of a picker I made worked, but it won't update, when I add a new group in the groups menu:

                        Picker("Please choose a color", selection: $selectedGroup) {
                            ForEach(0 ..< groups.count) {
                                Text(groups[$0].name).tag($0)
                                        }
                                    }

and the next thing I tried because of another post don´t works at all:

                        Picker("select a group", selection: $selectedGroup) {
                                        ForEach(groups, id: \.self) {
                                            Text(groups[$0].name).tag($0)
                                        }
                                    }

Here is the Array and struct I used for "groups":

struct Group: Identifiable{
    let id =  UUID()
    var name: String
    var members: Array<Member>
   
}


// AND:

var groups : [Group] = [Group = Group(name: "sample", members: [Member(name: "sample guy", sex: "m")])]

Solution

  • try something like this:

    struct Group: Identifiable, Hashable {
        let id = UUID()
        var name: String
        var members: [Member]
    }
    
    struct ContentView: View {
        @State var selectedGroup: Group?
        @State var groups: [Group] = [Group(name: "sample", members: [Member(name: "sample guy", sex: "m")])]
    
        var body: some View {
            Button(action: {
                // add a new group with a random name to `groups`
                groups.append(Group(name: UUID().uuidString, members: []))
            }) {
                Text("Add new group")
            }
            Picker("select a group", selection: $selectedGroup) {
                ForEach(groups) { group in
                    Text(group.name).tag(group)
                }
            }
        }
    }
    

    I suggest you read again Apple's SwiftUI Tutorials https://developer.apple.com/tutorials/swiftui