SwiftUI: Picker doesn't update text in same view

十年热恋 提交于 2021-01-27 20:58:07

问题


I have this simple situation:

struct User: Hashable, Identifiable {
    var id: Int
    var name: String
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

let bob = User(id: 1, name: "Bob")
let john = User(id: 2, name: "John")
let users = [bob, john]

struct ParentView: View {    
    @State private var user: User?

    var body: some View {
        VStack(spacing: 0) {
            // Other elements in view...
            Divider()
            ChildPickerView(user: $user)
            Spacer()
        }
    }    
}

struct ChildPickerView: View {
    @Binding var user: User?
    
    var body: some View {
        HStack {
            Text("Selected : \(author?.name ?? "--")")
            Picker(selection: $user, label: Text("Select a user")) {
                ForEach(0..<users.count) {
                    Text(users[$0].name)
                }
            }
        }
        .padding()
    }
}

When I select another value in the picker, the name in the Text() above isn't updated. However, when tapping the picker again, there is a tick near the selected user, which means the value has actually been selected. Why is the text not updated then?

Thank you for your help


回答1:


Type of selection and picker content id or tag should be the same. Find below fixed variant.

Tested with Xcode 12.1 / iOS 14.1.

    VStack {
        Text("Selected : \(user?.name ?? "--")")
        Picker(selection: $user, label: Text("Select a user")) {
            ForEach(users) {
                Text($0.name).tag(Optional($0))
            }
        }
    }


来源:https://stackoverflow.com/questions/64859421/swiftui-picker-doesnt-update-text-in-same-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!