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) }
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.
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.
@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.
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.
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") } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With