1

I created a custom button with Y and N options. (I could not use the Toggle button as I needed no options being selected at the beginning.

If the button is added in a Vstack it is working perfectly fine. Pressed option is being highlighted, the other option is dimmed.

But when it is added in a list view, when any button is clicked, it looks like whole cell is clicked and always the second option is being selected. How can I fix the issue?

enter image description here import SwiftUI

struct ContentView: View {

    var body: some View {

        VStack{
            MultiSelectionButtonView()

            Form{
                MultiSelectionButtonView()

                MultiSelectionButtonGroup()
            }
        }
    }
}


struct MultiSelectionButtonView: View {

    var body: some View {
        HStack{
            Text("Question")
            Spacer()
            MultiSelectionButtonGroup()

        }
    }
}

struct MultiSelectionButtonGroup: View {
    @State private var selectedOption : Int = 0

    var body: some View {

        HStack (spacing: 0){
            MultiSelectionButton(tag: 1, text: "Y", selectedOption: $selectedOption)
            MultiSelectionButton(tag: 2, text: "N", selectedOption: $selectedOption)
        }

    }
}

struct MultiSelectionButton: View {

    @State var tag : Int
    @State var text : String
    @Binding var selectedOption : Int


    var shapeSize : CGFloat = CGFloat(35)
    var strokeWidth : CGFloat = CGFloat(0.5)
    var cornerRadius : CGFloat = CGFloat(2)

    var colorSelected : Color = Color.green
    var colorNoSelected : Color = Color.gray.opacity(0.5)
    var colorStroke : Color = Color.gray

    var body: some View {


        Button(action: {
            self.selectedOption = self.tag
        }) {
            ZStack{
                Group {
                    RoundedRectangle(cornerRadius: self.cornerRadius, style: .continuous)
                        //Circle()
                        .fill((self.selectedOption == self.tag) ? colorSelected : colorNoSelected )

                    RoundedRectangle(cornerRadius: self.cornerRadius, style: .continuous)
                        //Circle()
                        .stroke(colorStroke, lineWidth: strokeWidth)
                }
                .frame(width: shapeSize, height: shapeSize)

                Text(text)
                    .font(.subheadline)
                    .fontWeight(.light)
                    .foregroundColor(Color.white)
            }
        }
    }
}
Musti
  • 63
  • 7

1 Answers1

0

check this answer here:

SwiftUI - Multiple Buttons in a List row

and try the borderlessbuttonstyle

Chris
  • 7,579
  • 3
  • 18
  • 38