Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transition to a new view controller with code only using Swift

Tags:

ios

swift

I want to transition from ViewController to secondViewController, when the user presses a UIButton, using code only in Swift.

//Function to transition func transition(Sender: UIButton!) {        //Current Code, default colour is black     let secondViewController:UIViewController = UIViewController()     self.presentViewController(secondViewController, animated: true, completion: nil)   } 
like image 618
Stephen Fox Avatar asked Jun 11 '14 15:06

Stephen Fox


1 Answers

The problem is that your code is creating a blank UIViewController, not a SecondViewController. You need to create an instance of your subclass, not a UIViewController,

func transition(Sender: UIButton!) {        let secondViewController:SecondViewController = SecondViewController()      self.presentViewController(secondViewController, animated: true, completion: nil)   } 

If you've overridden init(nibName nibName: String!,bundle nibBundle: NSBundle!) in your SecondViewController class, then you need to change the code to,

let sec: SecondViewController = SecondViewController(nibName: nil, bundle: nil) 
like image 66
rdelmar Avatar answered Oct 21 '22 05:10

rdelmar