【问题标题】:Changing value of two-dimensional lists (SwiftUI)Changing value of two-dimensional lists (SwiftUI)
【发布时间】:2022-12-01 21:06:07
【问题描述】:

I've a two-dimensional list and I want to change the value date as soon as the user starts taping. I tried it with contact.date = "31/02", but it doesn't work. Instead the message Cannot assign to property: 'contacts' is a 'let' constant keeps appearing.

struct ContactGroup: Identifiable {
    let id = UUID()
    let name: String
    let contacts: [Contact]
}

struct Contact: Identifiable {
    let id = UUID()
    let name: String
    var date: String
}

struct DashBoardView: View {
    let contactGroups: [ContactGroup] = [
        ContactGroup(
            name: "Favourite",
            contacts: [
                Contact(name: "John", date: "01/12"),
                Contact(name: "Foo", date: "18/06"),
                Contact(name: "Bar", date: "08/02")
            ]),
        ContactGroup(
            name: "Network Security",
            contacts: [
                Contact(name: "Alice", date: "31/07"),
                Contact(name: "Bob", date: "31/10"),
            ]),

    ]

    var body: some View {
        List(contactGroups) { group in
            Section {
                ForEach(group.contacts) { contact in
                    VStack {
                        Text(contact.name)
                        Text(contact.date)
                    }.onTapGesture {
                        // Doesn't work!
                        contact.date = "31/02"
                        // Doesn't work!
                        group.contacts[0].date = "31/02"
                        print(contact.date)
                    }
                }
            } header: {
                Text(group.name)
            }
        }
    }
}

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    Try changing

    @State var contactGroups: [ContactGroup]
    
    List($contactGroups) { $group in
    
    ForEach($group.contacts) { $contact in
    
    var contacts: [Contact]
    

    Check out Demystify SwiftUI from #wwdc21 https://developer.apple.com/wwdc21/10022

    【讨论】:

    • It doesn't work, the error message still appears
    • @Bassam do the same for the ForEach
    猜你喜欢
    • 2022-12-02
    • 2022-11-20
    • 1970-01-01
    • 2022-11-09
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2022-11-09
    相关资源
    最近更新 更多