Search code examples
iosswiftuikitswiftui-form

What do we have as UIButton(Sender: UIButton) in swiftui?


in the UIKit I catch the button sender (which button is clicked) via code

       let colorVC = UIColorPickerViewController()
       colorVC.delegate = self
       clickedButton = sender
       present(colorVC, animated: true)
   }

I want to accomplish the same in SwiftUI.

Where flagList.name comes from struct and I would like to catch which button was clicked so I can adjust the Flag name accordingly.

``` Button(action: {
            
            print("tapped")
        }, label: {
            List(flagList) { flagList in
             
                
                
                HStack(spacing: 15){
                Image(flagList.flagName)
                    .resizable()
                    .scaledToFit()
                    .clipShape(Circle())
                    .frame(width: 30, height: 30, alignment: .trailing)
                    
               
                    
                Text(flagList.name)
                    
                    .font(.system(size: 25, weight: .light, design: .default))

                }
            }



Solution

  • First, I think your button is in the wrong place. You probably want a list of buttons, not a button that consists of a list.

    Then, you can store a property that represents the currently selected button:

    @State var currentSelectedFlagName: String
    

    Note that I say represents, not stores. In SwiftUI, you shouldn't store references to individual views (including buttons).

    You can then set currentSelectedFlagName to the current selected flag name when it's tapped.

    struct ContentView: View {
        
        ...
        
        /// represents current selected button
        @State var currentSelectedFlagName: String
        
        var body: some View {
            List(flagList) { flagList in
                Button(action: {
    
                    /// set the property
                    currentSelectedFlagName = flagList.flagName
                    print("tapped")
                }) {
                    HStack(spacing: 15){
                        Image(flagList.flagName)
                            .resizable()
                            .scaledToFit()
                            .clipShape(Circle())
                            .frame(width: 30, height: 30, alignment: .trailing)
                        
                        Text(flagList.name)
                            .font(.system(size: 25, weight: .light, design: .default))
                        
                    }
                }
            }
        }
    }