How do I create a view controller file after creating a new view controller?
Asked Answered
F

2

88

I am developing a tabbed application.

When I create a new view controller and link it to the tab bar controller, unlike the other two default view controllers, this one has no viewcontroller.swift file.

How can I create this file?

I am using Xcode 6 and developing the app in Swift.

Fourhanded answered 18/2, 2015 at 15:42 Comment(0)
D
143

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

Daynadays answered 18/2, 2015 at 17:6 Comment(5)
Can you also create just a .swift file? Since your ViewController.swift will be the file for use in Swift.Commonly
Thanks, I meant that we could choose a Swift file from the pop up instead of the Cocoa Touch Class, correct?Commonly
Sure, but this does the same thing and adds the necessary import statements and sets the base class and gives you the template for a few methods. I'm not sure why you'd want to do that manually, but certainly you can if you want.Daynadays
If you're brave, you can actually skip Step #1 and, in Step #2, you can set the Custom Class to one of your existing view controller classes and have that view controller class handle the actions and outlets for both (or however many) scenes you set to that VC. Note that this has a lot of gotchas (starting with the fact that you need to check if an outlet is nil before you use it), and it's liable to introduce a lot of bugs if you try it for a large project, but it's a handy trick for small/toy/example apps.Marjorymarjy
Lol. If you see a light at the end of the tunnel, make sure it's not another train headed right for you at high speed. Technically you're right, of course, but OMG, you're just begging for problems, code maintenance headaches, etc.Daynadays
G
-2

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

Gallicize answered 10/8, 2017 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.