buttonswiftuiibaction

How to get a button sender id? in SwiftUI


                    Button(button1Name, action: messageMe)
                .frame(minWidth:0, maxWidth: 300)
                .padding()
                .foregroundColor(.white)
                .background(Color.gray)
                .cornerRadius(20)
                .tag("button1")
            
             }
         }
    }
}

func messageMe(//get sender) {
    print("Button Tag " //sender.id)
}

How can I get the tag of the button sent, so that I can run an action depending on which button was pressed? I know this is very basic, but cannot find a solution for SwiftUI. I'm back to developing after around 4 years and my beloved Objective-C is no more!


Solution

  • You can do it directly , without any needs of tag like that :

    Button("Button title 1") {
      print("Button tapped!")
      messageMe(buttonId :"1")
    }
    .frame(minWidth:0, maxWidth: 300)
    .padding()
    .foregroundColor(.white)
    .background(Color.gray)
    .cornerRadius(20)
    
    func messageMe(buttonId : String) {
      // use the buttonId
    }