我有这个代码:
import SwiftUI
struct PlayButton: View {
@Binding var isClicked: Bool
var body: some View {
Button(action: {
self.isClicked.toggle()
}) {
Image(systemName: isClicked ? "checkmark.circle.fill" : "circle")
}
}
}
struct ContentView: View {
@State private var isPlaying: Bool = false
var players : [String] = ["Crown" , "King" , "Queen" , "Prince"]
var body: some View {
VStack {
ForEach(players, id: \.self) { player in
HStack {
Text(player)
PlayButton(isClicked: $isPlaying)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如果我选择一个新按钮,我想取消选择所有其他以前选择的按钮。例如,如果我选择 King 并选择 Queen ,则取消选择 King 。我该怎么做
我做了什么。老实说,我无法提出解决方案。
答案 0 :(得分:0)
有关单个选择,一次可以传递到selectedData视图PLAYBUTTON
foo
答案 1 :(得分:0)
我知道这可能看起来像是提供答案的更多代码,但我的假设是您正在尝试制作一个真实世界的应用程序。一个真实世界的应用程序应该是可测试的,所以我的答案来自一个你可以测试你的逻辑与你的 UI 分开的地方。此解决方案允许您使用数据从模型的角度驱动您的视图正在执行的操作。
import SwiftUI
class PlayerModel {
let name: String
var isSelected : Bool = false
init(_ name: String){
self.name = name
}
}
class AppModel: ObservableObject {
let players : [PlayerModel] = [PlayerModel("Crown") , PlayerModel("King") ,PlayerModel("Queen") ,PlayerModel("Prince")]
var activePlayerIndex: Int?
init(){
}
func selectPlayer(_ player: PlayerModel){
players.forEach{
$0.isSelected = false
}
player.isSelected = true
objectWillChange.send()
}
}
struct PlayButton: View {
let isSelected: Bool
let action : ()->Void
var body: some View {
Button(action: {
self.action()
}) {
Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
}
}
}
struct ContentView: View {
@ObservedObject var model = AppModel()
var body: some View {
VStack {
ForEach(model.players, id: \.name) { player in
HStack {
Text(player.name)
PlayButton(isSelected: player.isSelected, action: { self.model.selectPlayer(player) })
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
PlayerView()
}
}