如何向右滑动以在Swift 3中显示新的View Controller?
我想能够在我的ViewController
,将显示另一个视图控制器, CommunitiesViewController
。
我已经看了其他线程,发现了一些这样做,虽然我相信他们是斯威夫特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的故事板ID。
但是,这不起作用,当我刷一下以下错误的应用程序崩溃:
libc ++ abi.dylib:以NSExceptiontypes的未捕获exception终止
错误的select器格式,更改为:
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) }
然后添加function:
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 } } }