Henry Brown
Henry Brown

Reputation: 2237

Presenting a a ViewController on a xib file in SWIFT

I have a xib file which I have created a pop up controller on a UIView. This pop up controller animates up when a button is pressed on a View Controller 1. I then have a button on the UIView which when pressed I want to present another View Controller (View Controller 2). code looks like:

class PopUpViewControllerSwift : UIViewController {

  @IBAction func goToVC2(sender: UIButton) {

        self.removeAnimate()

        let VC2: VC2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as VC2
        var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
        VC2.modalTransitionStyle = modalStyle
        presentViewController(VC2, animated: true, completion: nil)

    }
}

Although thou when the button is pressed it crashes, no error or callbacks or anything. Obviously this would normally work if it was just a regular View Controller but because I am doing it inside a pop Up View which has been animated on top of another View I think that is the problem?

Can anybody help?

thanks

Upvotes: 10

Views: 19770

Answers (3)

Ayush Gupta
Ayush Gupta

Reputation: 1077

It should be like this:

let vc = MyViewController(nibName: "MyViewController", bundle: nil)
present(vc, animated: true, completion: nil)

Upvotes: 0

Michael
Michael

Reputation: 9904

I did this in a UICollectionView didSelectItemAtIndexPath method.

// Register Nib
let newViewController = NewViewController(nibName: "NewViewController", bundle: nil)

// Present View "Modally"
self.present(newViewController, animated: true, completion: nil)

I set the ID of the ViewController to the same as the file name so I would be sure to reference the right ViewController.

Upvotes: 20

kilnyy
kilnyy

Reputation: 9

Make sure self.storyboard is not nil.

Also confirm that VC2 is one of the ViewController's identity in the storyboard file.

I hope it could help you.


if VC2 is in a storyboard file, try to use following command to get VC2

let storyboard = UIStoryboard(name: "YourStoryboardName(maybe 'Main')", bundle: nil)
let vc2 = storyboard.instantiateViewControllerWithIdentifier("VC2") as VC2

or if VC2 is in a nib file, try to use following command to get VC2

let vc2 = VC2(nibName: "YourNibName", bundle: nil)

Upvotes: 0

Related Questions