SwiftUI 列表正在工作,但选择器不起作用
Posted
技术标签:
【中文标题】SwiftUI 列表正在工作,但选择器不起作用【英文标题】:SwiftUI List is working but not the picker 【发布时间】:2020-07-26 15:42:59 【问题描述】:我有这个看法。该列表通过显示数据可以正常工作。选择器不工作。它不显示任何数据。两者都使用相同的对象和功能。我不知道选择器不显示数据的原因。我想使用选择器。我放置列表只是为了尝试确定问题,但我仍然不知道。
import SwiftUI
struct GameListPicker: View
@ObservedObject var gameListViewModel = GameListViewModel()
@State private var selectedGameList = ""
var body: some View
VStack
List(gameListViewModel.gameList)gameList in
HStack
Text(gameList.gameName)
.onAppear() self.gameListViewModel.fetchData()
Picker(selection: $selectedGameList, label: Text(""))
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)
这是游戏列表模型
import Foundation
struct GameListModel: Codable, Hashable,Identifiable
var id: String
//var id: String = UUID().uuidString
var gameName: String
提前感谢您的帮助
【问题讨论】:
【参考方案1】:Picker
不是动态设计的,所以数据更新时不会刷新,数据变化时尝试强制重建picker,如下图
Picker(selection: $selectedGameList, label: Text(""))
ForEach(gameListViewModel.gameList) gameList in
Text(gameList.gameName)
.id(gameListViewModel.gameList) // << here !!
【讨论】:
以上是关于SwiftUI 列表正在工作,但选择器不起作用的主要内容,如果未能解决你的问题,请参考以下文章