swiftUI选择器“通用结构“选择器”要求“字符串”符合“视图””

时间:2020-07-19 15:40:17

标签: swift swiftui

我遵循了对此链接的公认答案

How make work a Picker with an ObservedObject in SwiftUI?

但是我在GameListPicker结构中收到消息“通用结构'Picker'要求'String'必须符合'View'”

import SwiftUI

struct GameListPicker: View {
    
    @ObservedObject var gameListViewModel = GameListViewModel()
    @State private var selectedGameList = ""
    
    var body: some View {
     Picker(selection: $selectedGameList, label: ""){
            ForEach(gameListViewModel.gameList) { gameList in
                Text(gameList.gameName)
            }
        }
     .onAppear() {
            self.gameListViewModel.fetchData()
            }
    }
}

GameListViewModel

import Foundation
import Firebase

class GameListViewModel: ObservableObject{
    
    @Published var gameList = [GameListModel]()
    let db = Firestore.firestore()
    
    func fetchData() {

        db.collection("GameData").addSnapshotListener {(querySnapshot, error) in
        guard let documents = querySnapshot?.documents else {
          print("No documents")
          return
        }

        self.gameList = documents.map { queryDocumentSnapshot -> GameListModel in
          let data = queryDocumentSnapshot.data()
          let gameName = data["GameName"] as? String ?? ""
            return GameListModel(id: gameName, gameName: gameName)
        }
      }
    }
}

和gameListModel

import Foundation

struct GameListModel: Codable, Hashable,Identifiable {
    
    var id: String
    //var id: String = UUID().uuidString
    var gameName: String
    
}

我无法确定问题

2 个答案:

答案 0 :(得分:1)

您应该为View中的参数label:提供一个符合Picker协议的参数。

替换:

Picker(selection: $selectedGameList, label: "") {

使用:

Picker(selection: $selectedGameList, label: Text("")) {

答案 1 :(得分:1)

如果只需要文本,则可以使用:

Picker("Some text", selection: $selectedGameList) { ...

如果您不想为选择器添加任何标签(尝试使用""时),则可以使用EmptyView

Picker(selection: $selectedGameList, label: EmptyView()) { ...