在我的应用程序中,我需要两个播放器(只有 2 个名称/字符串),它们是从内置于 List/ForEach SwiftUI 代码中的数组中选择的,它们在另一个视图中使用。
将名称带入我的文本(项目)的字符串的方法是什么?
我可以从列表中选择两个项目吗?
感谢您的帮助。弗朗茨
我的代码(由 Ale Patron 修改,使用 UserDefaults 对数组/列表进行编码和解码的教程):
@State private var allTeams: [PlayerItem] = []
@State private var newPlayer = ""
@State private var selectedPlayer = ""
@State private var selection: String?
struct PlayerItem: Identifiable {
var id = UUID()
let player: String
}
var body: some View {
VStack{
HStack {
TextField("Add Players/Teams...", text: $newPlayer)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
self.allTeams.append(PlayerItem(player: self.newPlayer))
self.newPlayer = ""
}) {
Image(systemName: "plus")
}
.padding(.leading, 5)
}.padding()
List{
ForEach(allTeams) { playerItem in
Text(playerItem.player)
}
.onTapGesture {
print("How can I select my first und my second player")
}
}
Text("Selected Player: \(selectedPlayer)")
}
}
}