iosswiftuibuttondelegationtarget-action

Swift: Protocol method as Action in target-action


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?


Solution

  • 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)