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

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”的参数引用了未暴露给Objective-C的实例方法“handlePan(recognizer:)”
有没有办法解决这个问题,而不是在视图控制器中添加handlePan方法?

最佳答案

您需要用@objc注释您的协议以将其公开到Objective-C运行库:

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

关于swift - 协议(protocol)中的使用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40553881/

10-15 15:13