0

在我的应用程序中,我需要两个播放器(只有 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)")
        
    }
}

}

4

1 回答 1

0

您应该将索引用于您正在尝试做的事情。尝试这个:

 ForEach(allTeams.indices) { i in
          Text(allTeams[i].player)
             .onTapGesture {
                print("How can I select my first und my second player")
                print("The selected player is \(allTeams[i].player). The second player is \(allTeams[i + 1].player)"
            }
        }

确保还检查所选玩家是否是数组中的最后一个并抓住它。否则,您可能会遇到越界错误。

于 2021-06-01T08:32:34.440 回答