Steven
Steven

Reputation: 53

How to perform segue from inside UIView

How can a prepare a segue properly from inside a UIView NOT UIViewController

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

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

Upvotes: 3

Views: 2362

Answers (4)

Sanjay Mali
Sanjay Mali

Reputation: 546

You need to tap gesture for 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)
}

Upvotes: -1

Dimitar Stefanovski
Dimitar Stefanovski

Reputation: 889

One of the solution is to add UITapGestureRecognizer to your button but from inside the 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!
}

Upvotes: -1

William Chen
William Chen

Reputation: 278

If the button is a subview of your view controller's view, you should be able to drag an IBAction onTouchUpInside from the button to your view controller. You can then initiate the segue from that method.

Upvotes: -1

Mundi
Mundi

Reputation: 80265

Your view should not handle a button tap. That should be handled by the controller. (This is why it is called "controller", while the UIView is called "view").

MVC as described by Apple.

Upvotes: 4

Related Questions