当我尝试在 Text() 中显示选择器的选定数据时,会出现一个名为“索引超出范围”的错误。
但是,当我评论显示所选数据的 Text() 时,它工作正常。以下是表单中选择器的代码。
struct VMPickerView: View {
@State var vmIndex = 0
@ObservedObject var stockViewModel = StockViewModel()
var body: some View {
let allVM = self.stockViewModel.arrKey
return VStack {
Form {
Section {
Picker(selection: $vmIndex, label: Text("Location")) {
ForEach(0..<allVM.count, id: \.self) {
Text(allVM[$0]).tag($0)
}
}
//Text(allVM[vmIndex])
}
}
}
}
}
下面是我评论“Text(allVM[vmIndex])”时我的应用程序的图像
下面是我用来从 firebase 检索数据并存储到数组中的代码。
class StockViewModel: ObservableObject {
@Published var itemList = [ItemList]()
@Published var arrKey = [String]()
init() {
retrieveAllVM()
}
func retrieveAllVM() {
var arrKey = [String]()
let ref = Database.database().reference().child("VM")
ref.observeSingleEvent(of: .value, with: { snapshot in
for items in snapshot.children {
let itemSnap = items as! DataSnapshot
let allKey = itemSnap.key
arrKey.append(allKey)
}
self.arrKey = arrKey
print(self.arrKey)
})
}
}
*更改后我的代码:
class StockViewModel: ObservableObject {
@Published var itemList = [ItemList]()
@Published var arrKey = [String]()
func retrieveAllVM() {
var arrKey = [String]()
let ref = Database.database().reference().child("VM")
ref.observeSingleEvent(of: .value, with: { snapshot in
for items in snapshot.children {
let itemSnap = items as! DataSnapshot
let allKey = itemSnap.key
arrKey.append(allKey)
}
DispatchQueue.main.async {
self.arrKey = arrKey
print(self.arrKey)
}
//self.arrKey = arrKey
})
}
}
struct VMPickerView: View {
@State var vmIndex = 0
@ObservedObject var stockViewModel: StockViewModel
var body: some View {
let allVM = self.stockViewModel.arrKey
return VStack {
Form {
Section {
Picker(selection: $vmIndex, label: Text("Location")) {
ForEach(0..<allVM.count, id: \.self) {
Text(allVM[$0]).tag($0)
}
}
//Text(allVM[vmIndex])
}
}
}.onAppear {
self.stockViewModel.retrieveAllVM()
}
}
}