I want to be able to swipe right in my ViewController
which will show another view controller, CommunitiesViewController
.
I have looked on other threads and found some ways of doing this though I believe they are for Swift 2.
This is the code I am using in my 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
}
}
}
I have given CommunitiesViewController
a storyboard ID of CommunitiesID
.
But this does not work and the app crashes when I swipe right with the following error:
libc++abi.dylib: terminating with uncaught exception of type NSException
Try with:
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)
}
then add the 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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With