Swift: 协议方法作为目标动作中的动作
Swift: Protocol method as Action in 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)
如果我想让多个客户端被一个按钮定位,如何解决这个问题?
你可以试试
cameraButton.addTarget(Service.shared, action: #selector(Service.shared.cameraButtonDidPress(_:)), for: .touchUpInside)
//
class Service {
static let shared = Service()
@objc func cameraButtonDidPress (_ sender:UIButton){
}
}
如果你制定了协议,它应该可以工作 @objc
@objc protocol CameraButtonDelegate: class {
func cameraButtonDidPress(_ sender: UIButton
}
并将选择器指定为协议方法
cameraButtonDidPress.addTarget(delegate, action: #selector(CameraButtonDelegate.cameraButtonDidPress), for: .touchUpInside)
我想要一个协议:
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)
如果我想让多个客户端被一个按钮定位,如何解决这个问题?
你可以试试
cameraButton.addTarget(Service.shared, action: #selector(Service.shared.cameraButtonDidPress(_:)), for: .touchUpInside)
//
class Service {
static let shared = Service()
@objc func cameraButtonDidPress (_ sender:UIButton){
}
}
如果你制定了协议,它应该可以工作 @objc
@objc protocol CameraButtonDelegate: class {
func cameraButtonDidPress(_ sender: UIButton
}
并将选择器指定为协议方法
cameraButtonDidPress.addTarget(delegate, action: #selector(CameraButtonDelegate.cameraButtonDidPress), for: .touchUpInside)