【发布时间】:2015-12-30 18:14:21
【问题描述】:
我的目标是不在我的所有控制器中编写滑动检测代码。所以我所做的就是像这样创建类:“Swipes”:
class Swipes{
private var leftController: String
private var rightController: String
private var target: UIViewController
init(leftController: String, rightController: String, target: UIViewController){
self.leftController = leftController
self.rightController = rightController
self.target = target
}
func initLeftRightSwipes(){
let swipeRight = UISwipeGestureRecognizer(target: target, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
target.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: target, action: "respondToSwipeGesture:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
target.view.addGestureRecognizer(swipeLeft)
}
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
print("swipe detected")
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier(rightController)
target.presentViewController(vc, animated: false, completion: nil)
case UISwipeGestureRecognizerDirection.Down:
print("Swiped down")
case UISwipeGestureRecognizerDirection.Left:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier(leftController)
target.presentViewController(vc, animated: false, completion: nil)
case UISwipeGestureRecognizerDirection.Up:
print("Swiped up")
default:
break
}
}
}
}
在我的视图控制器中:
let swipe = Swipes.init(leftController: "popularID", rightController: "newID", target: self)
swipe.initLeftRightSwipes()
但是这不起作用。我收到unrecognized selector sent to instance 错误,因为选择器指向的函数不在控制器中。是否可以处理控制器外部的滑动?我一直在研究,但一无所获。
我还尝试将 UISwipeGestureRecognizer 中的目标设置为 self,但将 view.addGestureRecognizer 中的视图设置为当前控制器的视图。那也失败了。
非常感谢任何帮助或指导。
【问题讨论】:
-
你可以通过手势识别将VC子类化为
ParentViewController,然后所有其他VC都是ParentViewController的子类,然后它会按照你的意愿执行该方法,如果你想要要继续使用上面的代码,我认为你必须创建并传递委托来告诉类执行