Display Name
Display Name

Reputation: 1035

Swift: Calling a segue from a different view controller delegate

I have a viewcontroller, from which i call a popover, in the popover i have a delegate which calls a function back in the main viewcontroller.

In this function i close the popover and want to load a different view controller,

the closing of the original popover works, if i do this

func KeypadDismissData(View: UIViewController, Password : String){
    View.dismissViewControllerAnimated(true, completion: nil)  
} 

However if i try and call the segue to load the new view controller with the code

func KeypadDismissData(View: UIViewController, Password : String){
    View.dismissViewControllerAnimated(true, completion: nil)
    self.performSegueWithIdentifier("LoginToMain", sender:nil)
}

i get the error

Warning: Attempt to present <UIViewController: 0x7fc768488900> on ... whose view is not in the window hierarchy!

Any ideas how i can get round this?

Thanks

Upvotes: 0

Views: 689

Answers (1)

Eendje
Eendje

Reputation: 8883

Not sure if I get your problem, but I can try:

You open a popover in your MainViewController. To dismiss this popover you use a delegate, dismissing this popover in your MainViewController. Right after the popover is dismissed, you want to segue to another view.

I recreated it and the code looks as follows:

MainViewController:

protocol DismissDelegate: class {
    func dismiss()
}

class ViewController: UIViewController, DismissDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func openButton(sender: UIButton) {
        let popoverViewController = storyboard?.instantiateViewControllerWithIdentifier("popoverViewController") as! PopoverViewController
        popoverViewController.modalPresentationStyle = .Popover
        popoverViewController.delegate = self
        popoverViewController.preferredContentSize = CGSize(width: 200, height: 260)
        popoverViewController.view.backgroundColor = UIColor.yellowColor()

        // Settings for the popover
        let popover = popoverViewController.popoverPresentationController!
        popover.sourceView = self.view
        popover.sourceRect = sender.frame
        popover.backgroundColor = UIColor.redColor()

        presentViewController(popoverViewController, animated: true, completion: nil)
    }

    func dismiss() {
        dismissViewControllerAnimated(true) {
            self.performSegueWithIdentifier("segue", sender: self)
        }
    }
}

PopoverViewController:

class PopoverViewController: UIViewController {

    weak var delegate: DismissDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func dismissButton(sender: UIButton) {
        delegate?.dismiss()
    }
}

The difference is, I've put the segue in the completion of dismissViewControllerAnimated

Upvotes: 0

Related Questions