Swift 3:发送到实例的无法识别的选择器 Xcode 8

Swift 3: Unrecognized selector sent to instance Xcode 8

我以编程方式创建了一个 UIView 并向其添加了 UIPanGestureRecognizer:

class ViewController: UIViewController{
    var preludeView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        initViews()
        createConstrants()

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector(("handleTap:")))
        preludeView.addGestureRecognizer(panGestureRecognizer)
    }

    func handleTap(recognizer: UIPanGestureRecognizer) {
        print("WORKING!!!!")
    }

    func initViews() {
        ...
    }

    func createConstrants() {
        ...
    }
}

但是当我触摸视图时 Xcode 抛出错误:

2016-07-13 09:24:29.918 Draft_Hypa_02[661:83024] -[Draft_Hypa_02.ViewController handleTap:]: unrecognized selector sent to instance 0x17d94a10 2016-07-13 09:24:29.921 Draft_Hypa_02[661:83024] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Draft_Hypa_02.ViewController handleTap:]: unrecognized selector sent to instance 0x17d94a10' * First throw call stack: (0x249cf91b 0x2416ae17 0x249d52b5 0x249d2ee1 0x248fe238 0x294ae9eb 0x290e984f 0x28f7aff1 0x294afd4f 0x28f3ba57 0x28f38017 0x28f78ec9 0x28f7867b 0x28f49125 0x28f476d3 0x24991dff 0x249919ed 0x2498fd5b 0x248df229 0x248df015 0x25ecfac9 0x28fb1189 0x93144 0x24587873) libc++abi.dylib: terminating with uncaught exception of type NSException

但是,如果我删除 handleTap 函数中的参数并删除 Selector(("handleTap:")) 中的冒号,一切正常!

已经花了一天时间尝试解决此问题,非常感谢您的帮助!

如果您使用的是 swift 3,您的 selector 应该是这样的

#selector(self.handleTap(recognizer:))

你应该用不同的方式写这个声明。 使用以下行

let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:)))

而不是

let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector(("handleTap:")))

新方式

let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(YourViewController.handleTap(_:)))

class ViewController: UIViewController {

    let customView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        customView.addGestureRecognizer(panGestureRecognizer)
    }

    func handleTap(panGesture: UIPanGestureRecognizer) {

    }
}

不要忘记将您的自定义 UIView 添加到 VC。