Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

swift - Deselect all other Button selection if new one is selected

I have this code :

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()
  }
}

I want to deselect all other previously selected buttons if i select a new one. For example , if i select King and select queen , then King is deselected. How can i do that

What i have done. I honestly could not come with a solution .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a single selection, at a time you can pass selectedData to PlayButton view

struct PlayButton: View {

    @Binding var selectedData: String
    var data: String

    var body: some View {
        Button(action: {
            selectedData = data
        }) {
            Image(systemName: data == selectedData ? "checkmark.circle.fill" : "circle")
        }
    }
}

struct ContentView: View {
    @State private var selectedPlayer: String = ""
    private var players : [String] = ["Crown" , "King" , "Queen" , "Prince"]

    var body: some View {
        VStack {
            ForEach(players.indices) { index in
                let obj = players[index]
                HStack {
                    Text(obj)
                    PlayButton(selectedData: $selectedPlayer, data: obj)
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...