ProfessorHelloKittyNr1
ProfessorHelloKittyNr1

Reputation: 189

Copying view controllers in Swift

Very novice Swift-programmer here. Awhile ago I created a modal pop-up (MP1) using a separate view controller. I now want to add a second pop-up (MP2) sharing many of the properties of the first one. I've managed to create a copy of the first one in the main storyboard (copy paste) but have a few questions on how to proceed.

1) Does this also copy the associated code from MP1? If so how do I find it? (sorry if this is a real beginners question).

2) Does swift treat it as a separate reference or will buttons etc triggering the first also trigger the second now?

3) I've managed to rename MP2 by editing the name in the list to the left of the screen (where all view controllers and all their items are displayed). Yet on the main storyboard (in the rectangle over the storyboard) it still has the name of MP1. How do I change this?

Upvotes: 1

Views: 429

Answers (1)

Vyrd
Vyrd

Reputation: 172

When you create a ViewController, it is linked to a ViewController class (a Swift file, put simply). When you copy a VC it will be linked to the same class as the first one.

You can check which class it is linked to by going to your storyboard and checking the tab on Utilities tab (the one on the far right) then clicking on the Identity inspector (the small icon that looks like an ID card) as shown on this screenshot; the class it is linked to appears as "Class XXXXX" at the top of the tab.

enter image description here

Edit - To answer the comment: I would make a class that inherits from UIViewController that would contain all the code that both VC's would use then make two separate classes that would inherit from that new class, then link each VC to the respective class you would need. Here is an example. Both MyNewViewController 1 and 2 inherit from ViewControllerWithCommonCode and my ViewControllers are linked to 1 and the other.

As a reminder, to inherit from a class in Swift the syntax is as follows:

class MyNewViewController : ViewControllerWithCommonCode {
    // ...
}

Separate ViewControllers

Upvotes: 1

Related Questions