To perform a segue by tapping a UIView
, you need to add a gesture recognizer. In my example I instantiate and added a Subclass
of UIView
programmatically :
viewDidLoad(){
// here we instantiate an object of our subclass
let customView = MyViewSubclass(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// here we add it to our ViewController
self.view.addSubview(customView)
// here we instantiate an object of gesture recognizer
let gestureRec = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
// here we add it to our custom view
customView.addGestureRecognizer(gestureRec)
}
func someAction(sender:UITapGestureRecognizer){
performSegueWithIdentifier("Whazzzzup", sender: self)
}
// Swift 3
func someAction(_ sender:UITapGestureRecognizer){
// this is the function that lets us perform the segue
performSegue(withIdentifier: "Whazzzup", sender: self)
}
If you don't have a Subclass
of UIView
, then you just add a UIView
...
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
Also you could of course just take your UIView
Outlet and add the gesture recognizer to it.
let gestureRec = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
myView.addGestureRecognizer(gestureRec)
To present a ViewController
without segue, you need to instantiate the ViewController:
func someAction(_ sender:UITapGestureRecognizer){
let controller = storyboard?.instantiateViewController(withIdentifier: "someViewController")
self.present(controller!, animated: true, completion: nil)
// swift 2
// self.presentViewController(controller, animated: true, completion: nil)
}
You need to set the withIdentifier
in your ViewController's Attribute Inspector:

In this example withIdentifier
would be: LandingVC
If you're using a UINavigationController
and want a back Button
, you push the ViewController
on the Navigation stack:
self.navigationController?.pushViewController(controller!, animated: true)