Swift: Protocol method as Action in target-action

1.9k Views Asked by At

I'd like to have a protocol:

protocol CameraButtonDelegate: class {
    func cameraButtonDidPress(_ sender: UIButton)
}

So, I could assign any client to a button, e.g.:

cameraButton.addTarget(delegate, action: #selector(cameraButtonDidPress), for: .touchUpInside)

However, it does not compile as I have to specify a particular function in action, e.g.:

cameraButton.addTarget(delegate, action: #selector(AAPLViewController.cameraButtonDidPress), for: .touchUpInside)

How to solve this issue, if I'd like to have multiple clients being targeted by a single button?

2

There are 2 best solutions below

2
On BEST ANSWER

It should work if you make the protocol @objc

@objc protocol CameraButtonDelegate: class {
    func cameraButtonDidPress(_ sender: UIButton
}

and specify the selector as protocol method

cameraButtonDidPress.addTarget(delegate, action: #selector(CameraButtonDelegate.cameraButtonDidPress), for: .touchUpInside)
4
On

You can try

cameraButton.addTarget(Service.shared, action: #selector(Service.shared.cameraButtonDidPress(_:)), for: .touchUpInside)

//

class Service {

   static let shared = Service()

    @objc func cameraButtonDidPress (_ sender:UIButton){


    }
}