'SwiftUI Picker not changing bounded value - is binding ok?
I have a view with
@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($0)
}
}
Text(myTask.priority)
}
}
where MyTask is a class with priority as a String variable.
For some reason choosing a different value in the picker doesn't change the value in priority.
Help?
EDIT:
The only important part of MyTask class is :
class MyTask:Identifiable,Codable{
var priority:String = ""
}
Are we allowed to bind to a child's variable?
Solution 1:[1]
Your problem (as vadian stated above) is that without conforming to Observable, MyTask isn't going to be able to update the view. Add on that conformance so that it looks like this:
class MyTask: Identifiable, Observable{
var priority:String = ""
}
Solution 2:[2]
This can be accomplished in a couple ways, with a StateObject
or an ObservableObject
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)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |