-2

This is from the custom cell:

img

This is from the Storyboard:

img

Anyone have any idea how to make these two buttons do the exact same action? Is it possible to make multiple buttons do one action?

Safeen Azad
  • 56
  • 1
  • 7

2 Answers2

2

I usually keep the backing UIViews and UIViewControllers very thin in my applications and I create classes that do the actual heavy lifting. This makes for cleaner code and easier reuse.

class Player {
     static func play() { // Static makes it easier to call from every class, assuming you only play one song at a time
          // play logic goes here
     }
}

class MyView: UIView {
     @IBAction func play() { // connect in IB in your .xib
          Player.play()
     }
}

class MyViewController: UIViewController {
     @IBAction func play() { // connect in IB in your storyboard
          Player.play()
     }
}
Lucas van Dongen
  • 9,328
  • 7
  • 39
  • 60
  • 1
    looks legit, I'm gonna try... – Safeen Azad Nov 08 '17 at 12:37
  • How did it go @Safeen Azad? – Lucas van Dongen Nov 12 '17 at 18:51
  • 1
    Thanks for the help @Departamento B. Well, I used a protocol instead of creating a class in order to get the data from child to parent. But as you mentioned above, I can use it to do the actual procedure and then use it in my classes. – Safeen Azad Nov 13 '17 at 19:31
  • That's a useful pattern as well in this case. It kind of depends how far the buttons are away from each other, passing delegate references can become pretty complicated if the two screens aren't very closely related. – Lucas van Dongen Nov 13 '17 at 22:06
1

You need two IBAction methods in separate classes (for cell and for view controller). If you want to minimize repeating code try to make a special class with this functionality and then call its method in two IBAction methods.

Also you can take a look at Command design pattern for this purpose.

Artem Kirillov
  • 1,132
  • 10
  • 25