Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get button pressed id on Swift via sender

Tags:

swift

uibutton

So I have a storyboard with 3 buttons I want to just create 1 action for all those 3 buttons and decide what to do based on their label/id...

Is there a way to get some kind of identifier for each button?

By the way they are images, so they don't have a title.

@IBAction func mainButton(sender: UIButton) {     println(sender) } 
like image 973
matt Avatar asked May 05 '15 07:05

matt


People also ask

How do I know which button is pressed in Swift?

cause first is you have to click from the 3 button after clicking from the 3 button then you will click idenfifywhichpressed button and this button will identify or print which button from the 3 was pressed. During setup, mark the button tag as 1,2,3... When your click action done, check the sender.

How can I check if UIButton is pressed?

You can use the following code. class ViewController: UIViewController { var gameTimer: Timer! @IBAction func btnClick(_ sender: Any) { let button = UIButton() if (button. isSelected) { print(" Not Selected"); } else { print(" Selected"); } } override func viewDidLoad() { super.

What does the @IBAction tag do?

@IBAction is similar to @IBOutlet , but goes the other way: @IBOutlet is a way of connecting code to storyboard layouts, and @IBAction is a way of making storyboard layouts trigger code. This method takes one parameter, called sender . It's of type UIButton because we know that's what will be calling the method.

What is IBAction in Swift?

Swift code is associated with graphical interface elements through the use of outlets and actions. An IB Outlet (short for Interface Builder outlet) is a graphical component that your code links to. An IB action is the reverse: It is a method in your code that a graphical component links to.


1 Answers

You can set a tag in the storyboard for each of the buttons. Then you can identify them this way:

@IBAction func mainButton(sender: UIButton) {     println(sender.tag) } 

EDIT: For more readability you can define an enum with values that correspond to the selected tag. So if you set tags like 0, 1, 2 for your buttons, above your class declaration you can do something like this:

enum SelectedButtonTag: Int {     case First     case Second     case Third } 

And then instead of handling hardcoded values you will have:

@IBAction func mainButton(sender: UIButton) {     switch sender.tag {         case SelectedButtonTag.First.rawValue:             println("do something when first button is tapped")         case SelectedButtonTag.Second.rawValue:             println("do something when second button is tapped")         case SelectedButtonTag.Third.rawValue:                                    println("do something when third button is tapped")         default:             println("default")     } } 
like image 164
Vasil Garov Avatar answered Sep 20 '22 06:09

Vasil Garov