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 s
@IBAction func buttonPressed(_ sender: UIButton) {
if sender.tag == 1 {
print("Button 1 is pressed")
}
}
In this case you can use NSObject
extension
Accessibility Element UIAccessibility
.
I have used accessibilityLabel
and accessibilityIdentifier
both are success in call and condition checking.
First
You can set a Accessibility Label
or Identifier
in the storyboard for each of the buttons in Identity inspector. Accessibility should be enabled.
To check/Identify button by
@IBAction func selectionPicker(_ sender: UIButton){
if sender.accessibilityLabel == "childType"{ //Check by accessibilityLabel
print("Child Type")
}
if sender.accessibilityIdentifier == "roomType"{ //Check by accessibilityIdentifier
print("Room Type")
}
performSegue(withIdentifier: "selectionViewSegue", sender:sender)
}
On Swift 3.2 and 4.0 with Xcode 9.0
Swift 3 Code: In xcode Please set tag for each button first to work following code.
@IBAction func threeButtonsAction(_ sender: UIButton) {
switch sender.tag {
case 1:
print("do something when first button is tapped")
break
case 2:
print("do something when second button is tapped")
break
case 3:
print("do something when third button is tapped")
break
default:
break
}
}
Use the outlets instead, tags clutter the code and make the readability way worse. Think about the poor developer that reads the code next and sees if sender.tag = 381 { // do some magic }
, it just won't make any sense.
My example:
class PhoneNumberCell: UITableViewCell {
@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var messageButton: UIButton!
@IBAction func didSelectAction(_ sender: UIButton) {
if sender == callButton {
debugPrint("Call person")
} else if sender == messageButton {
debugPrint("Message person")
}
}
[...]
}
You could also do this in a nice switch
as well, which would make it even better.
Tested on Swift 5.1
Given the case you labeled your buttons "1", "2", "3":
@IBAction func mainButton(sender: UIButton) {
switch sender.titleLabel?.text {
case "1":
print("do something when first button is tapped")
case "2":
print("do something when second button is tapped")
case "3":
print("do something when third button is tapped")
default:
() // empty statement or "do nothing"
}
}
I'm not a fan of any of the above:
switch sender as! NSObject {
case self.buttoneOne:
println("do something when first button is tapped")
case self.buttoneTwo:
println("do something when second button is tapped")
default:
println("default")
}