Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

theprizerevealed

macrumors regular
Original poster
Feb 26, 2016
183
12
I wish to add code to a new and separate view controller.
Does this code need to be inside a separate view controller class? I see that the first view controller has this code at the top:

Code:
import UIKit

class ViewController: UIViewController {
}

When adding code to the next view controller do you write at the bottom this bit of code or is there some way on the main storyboard to click on the Assistant Editor to see where to write this new code is typed?
 
You tap Command + N and create a new Swift file. Call it something like MyViewController.swift.

Inside of that file you want the standard view controller code & lifecycle methods. None of them are required though.

Code:
import UIKit

class MyViewController : UIViewController
{
   override func viewDidLoad()
   {
      super.viewDidLoad();

      // put code here to start loading info from the internet, etc.
   }

   override func viewDidAppear(animated: Bool)
   {
      super.viewDidAppear(animated);
  
      //put code here to specify some layout properties of your view, like frames and such.
   }

   override func didReceiveMemoryWarning()
   {
      super.didReceiveMemoryWarning();
  
      // put code here to handle low-memory situations
   }
}

You should know, you don't actually even need to define a class for a new view controller. If it's very simple, in the Utilities sidebar (the right sidebar), at the bottom, one of the options will be the 'Objects' panel. Search for View Controller and simply drag the view controller in to your storyboard. This will create a new view controller for you.

Here is what it looks like (bottom right):

ss_example3.png
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.