SwiftUI:选择器不会在同一视图中更新文本 [英] SwiftUI: Picker doesn't update text in same view

查看:49
本文介绍了SwiftUI:选择器不会在同一视图中更新文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的情况:

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

当我在选择器中选择另一个值时,上面 Text() 中的名称不会更新.但是,当再次点击选择器时,所选用户附近有一个勾号,这意味着该值实际上已被选中.为什么文字没有更新?

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?

感谢您的帮助

推荐答案

选择类型和选择器内容 idtag 应该相同.找到以下固定变体.

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

使用 Xcode 12.1/iOS 14.1 测试.

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

这篇关于SwiftUI:选择器不会在同一视图中更新文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆