How to execute segue from inside UIView

How can I properly prepare segue from UIView NOT UIViewController

My UIViewController has a container view and there is a button inside that container view.

class myInnerView: UIView {
    ...
    func myButton(gesture: UIGestureRecognizer){
        //calling a perform segue from another UIViewController does not recognize the SegueID
        //ViewController().self.showProfile(self.id) -- DOES NOT WORK
    }
}

class ViewController: UIViewController {
    ...
    func showProfile(id: String){
        ...
        self.performSegueWithIdentifier("toViewProfile", sender: self)
    }
}

      

+3


source to share


4 answers


There should be no button click in your view. This must be controlled by the controller. (This is why it is called "controller" and UIView

called "view").



MVC as described by Apple .

+4


source


If the button is the view of your view controller, you can drag the IBAction onTouchUpInside from the button to your view controller. Then you can initiate segue from this method.



-1


source


One solution is to add UITapGestureRecognizer

to your button, but from the inside UIViewController

:

class ViewController: UIViewController {

    var myInnerView = myInnerView()

    override func viewDidLoad() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTapGesture))
        self.myInnerView.myButton.addGestureRecognizer(tap)
    }

    @objc func handleTapGesture(){
        performSegue(withIdentifier: "toViewProfile", sender: nil)
    }
}

class myInnerView: UIView {
    // make outlet of your button so you can add the tapGestureRecognizer from your ViewController and thats all
    @IBOutlet public weak var myButton: UIButton!
}

      

-1


source


You need to press gesture to view to navigate

let customView = myInnerView()
let gestureRec = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
myView.addGestureRecognizer(customView)


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)
}

      

-1


source







All Articles