[英]Why does picker binding not update when using SwiftUI?
我剛剛開始學習 Swift(甚至在 Swift UI 上更新。)所以如果這是一個新手錯誤,我們深表歉意。
我正在嘗試編寫一個非常簡單的程序,用戶從選擇器中選擇某人的名字,然后在下面看到顯示該人問候的文本。
但是,當使用選擇器選擇新值時,綁定的 var selectedPerson 不會更新。 這意味着即使我選擇了一個人,也不會顯示像“Hello Harry”這樣的問候語,而是顯示“Hello no-one”。
struct ContentView: View {
var people = ["Harry", "Hermione", "Ron"]
@State var chosenPerson: String? = nil
var body: some View {
NavigationView {
Form {
Section {
Picker("Choose your favourite", selection: $chosenPerson) {
ForEach ((0..<people.count), id: \.self) { person in
Text(self.people[person])
}
}
}
Section{
Text("Hello \(chosenPerson ?? "no-one")")
}
}
}
}
}
(我已經包含了一兩塊原始格式,以防有所不同)
我看過這個問題,似乎它可能是一個類似的問題,但是將.tag(person)
添加到Text(self.people[person])
並沒有解決我的問題。
如何獲得顯示所選人員姓名的問候語?
綁定到索引,而不是字符串。 使用選擇器,您不會做任何會改變字符串的事情。 選擇器更改時發生的變化是選定的索引。
struct ContentView: View {
var people = ["Harry", "Hermione", "Ron"]
@State var chosenPerson = 0
var body: some View {
NavigationView {
Form {
Section {
Picker("Choose your favourite", selection: $chosenPerson) {
ForEach(0..<people.count) { person in
Text(self.people[person])
}
}
}
Section {
Text("Hello \(people[chosenPerson])")
}
}
}
}
}
如果您使用的是簡單的 arrays,則接受的答案是正確的,但它對我不起作用,因為我使用的是自定義 model 結構數組,其中 id 定義為字符串,在這種情況下,選擇必須與此類型相同ID。 例子:
struct CustomModel: Codable, Identifiable, Hashable{
var id: String // <- ID of type string
var name: String
var imageUrl: String
然后,當您要使用選擇器時:
struct UsingView: View {
@State private var chosenCustomModel: String = "" //<- String as ID
@State private var models: [CustomModel] = []
var body: some View {
VStack{
Picker("Picker", selection: $chosenCustomModel){
ForEach(models){ model in
Text(model.name)
.foregroundColor(.blue)
}
}
}
希望它可以幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.