[英]SwiftUI | Access PickerView selection from another SwiftUI View
我厭倦了為動態選擇器構建基於user3441734 解決方案的多組件選擇器。 這個選擇器存在於它自己的.swift 文件中。 我不知道如何將選擇保存在變量中以再次從另一個視圖訪問它。
到目前為止,這是我的代碼。 我在下面用 an 及其錯誤消息標記了我的錯誤解決方案。
import SwiftUI
struct DynamicPicker: View {
@ObservedObject var model = Model()
// var to store the selection
@State var selection: String = ""
var body: some View {
VStack {
GeometryReader { geometry in
HStack {
Picker(selection: self.$model.selectedManufacturer, label: Text("")){
ForEach(0 ..< self.model.manufacturerNames.count){ index in
Text(self.model.manufacturerNames[index])
}
}.labelsHidden()
.frame(maxWidth: geometry.size.width * CGFloat(0.3333))
.clipped()
Picker(selection: self.$model.selectedStock, label: Text("")){
ForEach(0 ..< self.model.stockNamesCount){ index in
Text(self.model.stockNames[index])
}
}
.id(self.model.id)
.labelsHidden()
.frame(maxWidth: geometry.size.width * CGFloat(0.6666))
.clipped()
}
}
// Show selection
Text("\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])")
// Save selection to variable 🛑
selection = "\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])"
}
}
}
類型 '()' 不能符合 'View'; 只有結構/枚舉/類類型可以符合協議
不需要額外選擇,因為選擇已經存儲在model中,所以
1)刪除這些行
@State var selection: String = ""
// Save selection to variable 🛑
selection = "\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])"
2)不要創建內聯model,只需聲明它能夠通過構造函數注入
struct DynamicPicker: View {
@ObservedObject var model: Model // << here !!
3)對其他依賴視圖的DynamicPicker使用相同的DynamicPicker
,假設它被稱為ManufacturerView
(聲明了與上面相同的觀察到的model)。 並且有一些根視圖持有兩者,所以它可能是
struct RootView: View {
let model = Model() // << create it here
var body: some View {
VStack {
DynamicPicker(model: self.model)
ManufacturerView(model: self.model)
}
}
}
所以當在DynamicPicker
中更新選擇時, ManufacturerView
將自動更新相應的選擇,因為使用相同的數據源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.