ryohei ryohei - 1 year ago 57
Swift Question

Is there any way to connect a UIView to a UIViewControoler?

I wonder if it is possible to conenct a

property to a UIViewController. By connecting a
, I want to transition to a second view controller. I have attempted several times by dragging and coding, but I just faild. I am looking for ways that do not need to program like using seague.

Is there anything that achievs this goal?


Answer Source

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 :


    // 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

    // 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

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 (_:)))

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:

enter image description here

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download