【问题标题】:Swift: Protocol method as Action in target-actionSwift:协议方法作为目标动作中的动作
【发布时间】:2019-01-21 04:07:50
【问题描述】:

我想要一个协议:

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)

如果我想让一个按钮定位多个客户端,如何解决这个问题?

【问题讨论】:

    标签: ios swift uibutton delegation target-action


    【解决方案1】:

    如果您制定协议@objc,它应该可以工作

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

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

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

    【讨论】:

    • 如果最终实现会写在类里面,那么这里需要什么委托
    • 像魅力一样工作。
    【解决方案2】:

    你可以试试

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

    //

    class Service {
    
       static let shared = Service()
    
        @objc func cameraButtonDidPress (_ sender:UIButton){
    
    
        }
    }
    

    【讨论】:

    • 谢谢,我正在寻找更优雅的解决方案,避免使用单例。
    • 如果重复并解决了您的问题,请删除
    • 这并不是因为 Swift 语法发生了显着变化,并且该答案中描述的方法不再起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多