0

我目前正在 swift ui 中开发一个应用程序。在应用程序中是添加组的功能,在主屏幕上您可以选择其中一个组。我的问题是,我制作的选择器的一个选项有效,但是当我在组菜单中添加一个新组时它不会更新:

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

由于另一篇文章,我尝试的下一件事根本不起作用:

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

这是我用于“组”的数组和结构:

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")])]
4

1 回答 1

0

尝试这样的事情:

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)
            }
        }
    }
}

我建议你再读一遍 Apple 的 SwiftUI 教程https://developer.apple.com/tutorials/swiftui

于 2022-02-07T06:43:37.100 回答