[英]Using ForEach inside a Picker
我在使用 SwiftUI 將數據從數組中提取到選擇器時遇到問題。 我可以正確地列出我感興趣的數據,但似乎無法使相同的邏輯工作以將數據拉入選擇器。 我已經用幾種不同的方式對其進行了編碼,但是我目前的方式給出了這個錯誤:
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Text' conform to 'TableRowContent'
代碼如下:
import SwiftUI
struct BumpSelector: View {
@ObservedObject var model = ViewModel()
@State var selectedStyle = 0
init(){
model.getData2()}
var body: some View {
VStack{
List (model.list) { item in
Text(item.style)}
Picker("Style", selection: $selectedStyle, content: {
ForEach(0..<model.list.count, content: { index in
Text(index.style)
})
})
}
}
model 在這里:
import Foundation
struct Bumps: Identifiable{
var id: String
var style: String
}
ViewModel 在這里:
import Foundation
import Firebase
import FirebaseFirestore
class ViewModel: ObservableObject {
@Published var list = [Bumps]()
@Published var styleArray = [String]()
func getData2() {
let db = Firestore.firestore()
db.collection("bumpStop").getDocuments { bumpSnapshot, error in
//Check for errors first:
if error == nil {
//Below ensures bumpSnapshot isn't nil
if let bumpSnapshot = bumpSnapshot {
DispatchQueue.main.async {
self.list = bumpSnapshot.documents.map{ bump in
return Bumps(id: bump.documentID,
style: bump["style"] as? String ?? "")
}
}
}
}
else {
//Take care of the error
}
}
}
}
ForEach
中的index
只是一個Int
,沒有與Int
關聯的樣式。 您可以嘗試這種方法來使Picker
與其ForEach
一起工作:
struct BumpSelector: View {
@ObservedObject var model = ViewModel()
@State var selectedStyle = 0
init(){
model.getData2()
}
var body: some View {
VStack{
List (model.list) { item in
Text(item.style)}
Picker("Style", selection: $selectedStyle) {
ForEach(model.list.indices, id: \.self) { index in
Text(model.list[index].style).tag(index)
}
}
}
}
}
編輯-1:
Text(model.list[selectedStyle].style)
將為您提供selectedStyle
所需的style
。 但是,在使用索引時,您需要確保它在使用時是有效的。 也就是說,使用if selectedStyle < model.list.count { Text(model.list[selectedStyle].style) }
。
您也可以使用這種不使用index
的替代方法:
struct Bumps: Identifiable, Hashable { // <-- here
var id: String
var style: String
}
struct BumpSelector: View {
@ObservedObject var model = ViewModel()
@State var selectedBumps = Bumps(id: "", style: "") // <-- here
init(){
model.getData2()
}
var body: some View {
VStack{
List (model.list) { item in
Text(item.style)
}
Picker("Style", selection: $selectedBumps) {
ForEach(model.list) { bumps in
Text(bumps.style).tag(bumps) // <-- here
}
}
}
.onAppear {
if let first = model.list.first {
selectedBumps = first
}
}
}
}
然后使用selectedBumps
,就像任何Bumps
一樣,例如selectedBumps.style
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.