Swift:协议方法作为目标操作中的操作

时间:2018-08-14 10:17:12

标签: ios swift uibutton delegation target-action

我想要一个协议:

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

因此,我可以将任何客户端分配给按钮,例如:

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

但是,它不能编译,因为我必须在action中指定特定的函数,例如:

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

如果我想通过一个按钮将多个客户作为目标,该如何解决此问题?

2 个答案:

答案 0 :(得分:4)

如果您制定协议@objc

,它应该可以正常工作
@objc protocol CameraButtonDelegate: class {
    func cameraButtonDidPress(_ sender: UIButton
}

并指定选择器作为协议方法

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

答案 1 :(得分:0)

您可以尝试

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

//

class Service {

   static let shared = Service()

    @objc func cameraButtonDidPress (_ sender:UIButton){


    }
}