在协议中使用方法

时间:2016-11-11 18:16:00

标签: swift protocols selector

我已经创建了协议和协议的扩展:

protocol SomeProtocol: class {
    var someView: UIView { get set }

    func handlePan(recognizer: UIPanGestureRecognizer)
}

extension SomeProtocol where Self: UIViewController {
    func handlePan(recognizer: UIPanGestureRecognizer) {
        // implementation
    }
}

class SomeViewController: UIViewController, SomeProtocol {

    var someView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        someView.frame = CGRect(x: 100, y: 200, width: 50, height: 50)
        someView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan)))
        someView.backgroundColor = .black

        view.addSubview(someView)
    }
}

但是这给了我创建UIPanGestureRecognizer的错误:

  

错误:' #selector'的争论指实例方法' handlePan(识别器:)'没有暴露于Objective-C

有没有办法解决这个问题,而不是在视图控制器中添加handlePan方法?

1 个答案:

答案 0 :(得分:1)

您需要使用@objc注释协议,以将其公开给Objective-C运行时库:

@objc protocol SomeProtocol: class { //...