SwiftUI Picker 没有改变有界值 - 绑定可以吗?

SwiftUI Picker not changing bounded value - is binding ok?

我有一个观点

@State var myTask:MyTask
let priorities = ["","A","B","C","D","E","F","G","H","I","J","K"]

var body: some View{
    VStack{
           Picker("",selection: $myTask.priority) {
                ForEach(priorities.reversed(), id:\.self){
                   Text([=10=])
                }
           }
           Text(myTask.priority)
    }
}

其中 MyTask 是一个 class,优先级为字符串变量。

出于某种原因,在选择器中选择不同的值不会更改优先级中的值。

帮忙?

编辑:

MyTask class 唯一重要的部分是:

class MyTask:Identifiable,Codable{
    var priority:String = ""
    
}

我们可以绑定到 child 的变量吗?

您的问题(如上文 vadian 所述)是,如果不遵守 Observable,MyTask 将无法更新视图。添加一致性,使其看起来像这样:

class MyTask: Identifiable, Observable{
    var priority:String = ""
    
}

这可以通过多种方式实现,使用 StateObjectObservableObject class。

struct ContentView: View {
    @State var selection = "A"
    private var priorities = ["A", "B", "C", "D"]
    
    var body: some View {
        Picker("Selection", selection: $selection) {
            ForEach(priorities.reversed(), id: \.self) { priority in
                Text(priority)
            }
        }
        Text(selection)
    }
}
class MyTask: ObservableObject {
    @Published var selection = "A"
}

struct ContentView: View {
    @StateObject var task = MyTask()
    private var priorities = ["A", "B", "C", "D"]
    
    var body: some View {
        Picker("Selection", selection: $task.selection) {
            ForEach(priorities.reversed(), id: \.self) { priority in
                Text(priority)
            }
        }
        Text(task.selection)
    }
}