[英]SwiftUI Picker not changing selection when tapped
Here is my list of objects:这是我的对象列表:
let gameTypes = [
GameType(id: "generalKnowledge", text: "❓ General Knowledge"),
GameType(id: "geography", text: "🌎 Geography"),
GameType(id: "music", text: "🎤 Music"),
GameType(id: "sport", text: "⚽️ Sport"),
GameType(id: "technology", text: "💻 Technology"),
GameType(id: "movies", text: "📺 Movies & TV"),
]
And my Picker
in my view:在我看来,我的
Picker
:
@State var gameType: GameType = gameTypes[0]
var body: some View {
NavigationView {
VStack {
// Create game
HStack {
Picker("\(gameType.text)", selection: $gameType) {
ForEach(gameTypes, id: \.id){ type in
Text("\(type.text)").tag("\(type.id)")
}
}
.pickerStyle(MenuPickerStyle())
My Picker
successfully shows all gameTypes
items in a list/menu when tapped.点击时,我的
Picker
成功地在列表/菜单中显示所有gameTypes
项目。 However when I tap an item in that list, gameType
does not update.但是,当我点击该列表中的一个项目时,
gameType
不会更新。
Any idea why?知道为什么吗?
EDIT:编辑:
GameType游戏类型
class GameType: Hashable, Equatable {
let id: String
let text: String
init(id: String, text: String) {
self.id = id
self.text = text
}
// Conform to Hashable
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
// Conform to Equatable (players will not be the same)
static func == (lhs: GameType, rhs: GameType) -> Bool {
return false
}
}
This is because the GameType and Tag types are different.这是因为 GameType 和 Tag 类型不同。 And when selecting, swift does not work to assign an
Int
to the GameType
type.并且在选择时,swift 无法将
Int
分配给GameType
类型。 Just change your tag to the type
instead of type.id
and everything will work.只需将您的标签更改为
type
而不是type.id
,一切都会正常工作。 Example例子
HStack {
Picker("\(gameType.text)", selection: $gameType) {
ForEach(gameTypes, id: \.id) { type in
Text("\(type.text)").tag(type)
}
}
.pickerStyle(MenuPickerStyle())
}
here is a salvation, you need to use struc:这是一个救赎,你需要使用struc:
struct GameType: Hashable, Identifiable, Equatable {
let id: String
let text: String
init(id: String, text: String) {
self.id = id
self.text = text
}
static func == (lhs: GameType, rhs: GameType) -> Bool {
return lhs.id == rhs.id
}
}
let gameTypes = [
GameType(id: "generalKnowledge", text: "❓ General Knowledge"),
GameType(id: "geography", text: "🌎 Geography"),
GameType(id: "music", text: "🎤 Music"),
GameType(id: "sport", text: "⚽️ Sport"),
GameType(id: "technology", text: "💻 Technology"),
GameType(id: "movies", text: "📺 Movies & TV"),
]
import SwiftUI
struct ContentView: View {
@State var gameTypeSelected: String = gameTypes[3].id
var body: some View {
Picker(selection: $gameTypeSelected, label: Text("")) {
ForEach(gameTypes, id: \.id) { item in
Text(item.text).id(item.id)
}
}
Text("You selected: " + gameTypeSelected).bold()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.