Swift编程:手势识别器绑定导航控制器报错的解决问询
解决「Cannot find 'handleGesture' in scope」的问题
这个报错的根源是Swift的#selector在编译阶段会优先检查当前代码所在的作用域(也就是你的ViewController类)是否存在指定的方法,哪怕你已经把手势的target设置为ProfileNavigationController的实例,编译器还是会默认在ViewController的上下文里查找handleGesture方法,所以才会要求你在ViewController里加空实现才能通过编译。
下面给你两种靠谱的解决方法,优先推荐第一种:
方法一:明确指定Selector的类归属
直接在#selector里指定方法所属的类,告诉编译器去ProfileNavigationController类里找这个方法,这样就不用在ViewController里写空实现了:
guard let thisNavigationController = navigationController as? ProfileNavigationController else { return } let panDown = UIPanGestureRecognizer(target: thisNavigationController, action: #selector(ProfileNavigationController.handleGesture(_:))) panDown.delegate = self collectionView.addGestureRecognizer(panDown)
注意要把方法签名写完整,包括参数_:,因为你的handleGesture是带一个UIPanGestureRecognizer参数的。
方法二:使用Selector字符串(不推荐,编译期无检查)
如果你不想指定类归属,也可以用Objective-C风格的Selector字符串,不过这种方式编译器不会帮你检查方法是否存在,一旦方法名写错或者被删除,runtime才会报错,所以只作为备选:
guard let thisNavigationController = navigationController as? ProfileNavigationController else { return } let panDown = UIPanGestureRecognizer(target: thisNavigationController, action: Selector("handleGesture:")) panDown.delegate = self collectionView.addGestureRecognizer(panDown)
另外要提醒一句:确保ProfileNavigationController里的handleGesture方法是**@objc public或者@objc dynamic**修饰的,保证它能被Objective-C runtime识别到,这一点你已经做了,没问题。
内容的提问来源于stack exchange,提问作者StackGU
相关产品推荐
相关产品推荐

