\$\begingroup\$
\$\endgroup\$
1
I have an iOS Swift app with 8 buttons that call the same segue, but this is very repetitive. How can I refactor so it uses the same function prepare
?
@IBAction func backButtonPressed(_ sender: Any) {
self.vcWithType = VCtype.back.rawValue
self.postion = "back"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func mountButtonPressed(_ sender: Any) {
self.vcWithType = VCtype.mount.rawValue
self.postion = "mount"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func kneeRideButtonPressed(_ sender: Any) {
self.vcWithType = VCtype.knee.rawValue
self.postion = "knee"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func sideKbuttonPressed(_ sender: Any) {
self.vcWithType = VCtype.sideK.rawValue
self.postion = "side"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func northSouthBpressed(_ sender: Any) {
self.vcWithType = VCtype.northSouth.rawValue
self.postion = "north"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func guardBpressed(_ sender: Any) {
self.vcWithType = VCtype.guarda.rawValue
self.postion = "guard"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func halfGuardBpressed(_ sender: Any) {
self.vcWithType = VCtype.halfGuard.rawValue
self.postion = "half"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
@IBAction func turtleBpressed(_ sender: Any) {
self.vcWithType = VCtype.turtle.rawValue
self.postion = "turtle"
self.performSegue(withIdentifier: "showCategory", sender: sender)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showCategory") {
if let vc: CategoryViewController = segue.destination as? CategoryViewController {
vc.vcWithType = self.vcWithType
vc.chaza = self.postion
}
}
}
manuelBetancurtmanuelBetancurt
asked Feb 7, 2017 at 1:41
-
\$\begingroup\$ Create enum of your position, and instead of calling independent method on every button, call only one method. \$\endgroup\$Rahul Patel– Rahul Patel2017年02月07日 11:38:02 +00:00Commented Feb 7, 2017 at 11:38
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
I think easiest way is using tag
s.
You can connect more then one button to one IBAction func
. Just Make sure sender is UIButton.
After that change buttons tag property.
After changing tags. We just need to use switch-case
@IBAction func ButtonAction(_ sender: UIButton) {
switch sender.tag {
case 0:
print("Button 1 Clicked")
case 1:
print("Button 2 Clicked")
default: break
}
}
-
\$\begingroup\$ You can set the tag programmatically if you don't want to dig around in Interface Builder setting them. To reduce the chance of typos, you might want to use an
enum
to store your tags and reference the enum when setting the button tags. \$\endgroup\$Adrian– Adrian2017年02月23日 19:07:47 +00:00Commented Feb 23, 2017 at 19:07
default