如何在 Swift 3 中向右滑动以显示新的视图控制器?

How to swipe right to show new View Controller in Swift 3?

我希望能够在 ViewController 中向右滑动,这将显示另一个视图控制器 CommunitiesViewController

我查看了其他线程并找到了一些方法,尽管我相信它们适用于 Swift 2.

这是我在 ViewController:

中使用的代码
override func viewDidLoad() {
    super.viewDidLoad()

    let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector(("respondToSwipeGesture")))
    swipeRight.direction = UISwipeGestureRecognizerDirection.right
    self.view.addGestureRecognizer(swipeRight)
}

  func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    print ("Swiped right")

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.right:


            //change view controllers

            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

            let resultViewController = storyBoard.instantiateViewController(withIdentifier: "CommunitiesID") as! CommunitiesViewController

            self.present(resultViewController, animated:true, completion:nil)    


        default:
            break
        }
    }
}

我已经给 CommunitiesViewController 一个故事板 ID CommunitiesID

但这不起作用,当我向右滑动时应用程序崩溃并出现以下错误:

libc++abi.dylib: terminating with uncaught exception of type NSException

错误的选择器格式,更改为:

action: #selector(respondToSwipeGesture)
func respondToSwipeGesture(gesture: UIGestureRecognizer)

action: #selector(respondToSwipeGesture(_:))
func respondToSwipeGesture(_ gesture: UIGestureRecognizer)

试试:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // Gesture Recognizer     
    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
    swipeRight.direction = UISwipeGestureRecognizerDirection.right

    self.view.addGestureRecognizer(swipeRight)
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
    swipeLeft.direction = UISwipeGestureRecognizerDirection.left
    self.view.addGestureRecognizer(swipeLeft)

}

然后添加函数:

func respondToSwipeGesture(gesture: UIGestureRecognizer) {
    if let swipeGesture = gesture as? UISwipeGestureRecognizer {
        switch swipeGesture.direction {
        case UISwipeGestureRecognizerDirection.right:
            //right view controller
            let newViewController = firstViewController() 
            self.navigationController?.pushViewController(newViewController, animated: true)
        case UISwipeGestureRecognizerDirection.left:
            //left view controller
            let newViewController = secondViewController() 
            self.navigationController?.pushViewController(newViewController, animated: true)
        default:
            break
        }
    }
}