Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use single storyboard uiviewcontroller for multiple subclass

great question - but unfortunately only a lame answer. I don't believe that it is currently possible to do what you propose because there are no initializers in UIStoryboard that allow overriding the view controller associated with the storyboard as defined in the object details in the storyboard on initialization. It's at initialization that all the UI elements in the stoaryboard are linked up to their properties in the view controller.

It will by default initialize with the view controller that is specified in the storyboard definition.

If you are trying to gain reuse of UI elements you created in the storyboard, they still must be linked or associated to properties in which ever view controller is using them for them to be able to "tell" the view controller about events.

It's not that much of a big deal copying over a storyboard layout especially if you only need a similar design for 3 views, however if you do, you must make sure that all the previous associations are cleared, or it will get crashes when it tries to communicate to the previous view controller. You will be able to recognize them as KVO error messages in the log output.

A couple of approaches you could take:

  • store the UI elements in a UIView - in a xib file and instantiate it from your base class and add it as a sub view in the main view, typically self.view. Then you would simply use the storyboard layout with basically blank view controllers holding their place in the storyboard but with the correct view controller sub class assigned to them. Since they would inherit from the base, they would get that view.

  • create the layout in code and install it from your base view controller. Obviously this approach defeats the purpose of using the storyboard, but may be the way to go in your case. If you have other parts of the app that would benefit from the storyboard approach, it's ok to deviate here and there if appropriate. In this case, like above, you would just use bank view controllers with your subclass assigned and let the base view controller install the UI.

It would be nice if Apple came up with a way to do what you propose, but the issue of having the graphic elements pre-linked with the controller subclass would still be an issue.

have a great New Year!! be well


The code of line we are looking for is:

object_setClass(AnyObject!, AnyClass!)

In Storyboard -> add UIViewController give it a ParentVC class name.

class ParentVC: UIViewController {

    var type: Int?

    override func awakeFromNib() {

        if type = 0 {

            object_setClass(self, ChildVC1.self)
        }
        if type = 1 {

            object_setClass(self, ChildVC2.self)
        }  
    }

    override func viewDidLoad() {   }
}

class ChildVC1: ParentVC {

    override func viewDidLoad() {
        super.viewDidLoad()

        println(type)
        // Console prints out 0
    }
}

class ChildVC2: ParentVC {

    override func viewDidLoad() {
        super.viewDidLoad()

        println(type)
        // Console prints out 1
    }
}

As the accepted answer states, it doesn't look like it is possible to do with storyboards.

My solution is to use Nib's - just like devs used them before storyboards. If you want to have a reusable, subclassable view controller (or even a view), my recommendation is to use Nibs.

SubclassMyViewController *myViewController = [[SubclassMyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; 

When you connect all your outlets to the "File Owner" in the MyViewController.xib you are NOT specifying what class the Nib should be loaded as, you are just specifying key-value pairs: "this view should be connected to this instance variable name." When calling [SubclassMyViewController alloc] initWithNibName: the initialization process specifies what view controller will be used to "control" the view you created in the nib.


It is possible to have a storyboard instantiate different subclasses of a custom view controller, though it involves a slightly unorthodox technique: overriding the alloc method for the view controller. When the custom view controller is created, the overridden alloc method in fact returns the result of running alloc on the subclass.

I should preface the answer with the proviso that, although I have tested it in various scenarios and received no errors, I can't ensure that it will cope with more complex set ups (but I see no reason why it shouldn't work). Also, I have not submitted any apps using this method, so there is the outside chance that it might be rejected by Apple's review process (though again I see no reason why it should).

For demonstration purposes, I have a subclass of UIViewController called TestViewController, which has a UILabel IBOutlet, and an IBAction. In my storyboard, I have added a view controller and amended its class to TestViewController, and hooked up the IBOutlet to a UILabel and the IBAction to a UIButton. I present the TestViewController by way of a modal segue triggered by a UIButton on the preceding viewController.

Storyboard image

To control which class is instantiated, I have added a static variable and associated class methods so get/set the subclass to be used (I guess one could adopt other ways of determining which subclass is to be instantiated):

TestViewController.m:

#import "TestViewController.h"

@interface TestViewController ()
@end

@implementation TestViewController

static NSString *_classForStoryboard;

+(NSString *)classForStoryboard {
    return [_classForStoryboard copy];
}

+(void)setClassForStoryBoard:(NSString *)classString {
    if ([NSClassFromString(classString) isSubclassOfClass:[self class]]) {
        _classForStoryboard = [classString copy];
    } else {
        NSLog(@"Warning: %@ is not a subclass of %@, reverting to base class", classString, NSStringFromClass([self class]));
        _classForStoryboard = nil;
    }
}

+(instancetype)alloc {
    if (_classForStoryboard == nil) {
        return [super alloc];
    } else {
        if (NSClassFromString(_classForStoryboard) != [self class]) {
            TestViewController *subclassedVC = [NSClassFromString(_classForStoryboard) alloc];
            return subclassedVC;
        } else {
            return [super alloc];
        }
    }
}

For my test I have two subclasses of TestViewController: RedTestViewController and GreenTestViewController. The subclasses each have additional properties and each override viewDidLoad to change the background colour of the view and update the text of the UILabel IBOutlet:

RedTestViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor redColor];
    self.testLabel.text = @"Set by RedTestVC";
}

GreenTestViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor greenColor];
    self.testLabel.text = @"Set by GreenTestVC";
}

On some occasions I might want to instantiate TestViewController itself, on other occasions RedTestViewController or GreenTestViewController. In the preceding view controller, I do this at random as follows:

NSInteger vcIndex = arc4random_uniform(4);
if (vcIndex == 0) {
    NSLog(@"Chose TestVC");
    [TestViewController setClassForStoryBoard:@"TestViewController"];
} else if (vcIndex == 1) {
    NSLog(@"Chose RedVC");
    [TestViewController setClassForStoryBoard:@"RedTestViewController"];
} else if (vcIndex == 2) {
    NSLog(@"Chose BlueVC");
    [TestViewController setClassForStoryBoard:@"BlueTestViewController"];
} else {
    NSLog(@"Chose GreenVC");
    [TestViewController setClassForStoryBoard:@"GreenTestViewController"];
}

Note that the setClassForStoryBoard method checks to ensure that the class name requested is indeed a subclass of TestViewController, to avoid any mix-ups. The reference above to BlueTestViewController is there to test this functionality.


try this, after instantiateViewControllerWithIdentifier.

- (void)setClass:(Class)c {
    object_setClass(self, c);
}

like :

SubViewController *vc = [sb instantiateViewControllerWithIdentifier:@"MainViewController"];
[vc setClass:[SubViewController class]];

Basing particularly on nickgzzjr and Jiří Zahálka answers plus comment under the second one from CocoaBob I've prepared short generic method doing exactly what OP needs. You need only to check storyboard name and View Controllers storyboard ID

class func instantiate<T: BasicViewController>(as _: T.Type) -> T? {
        let storyboard = UIStoryboard(name: "StoryboardName", bundle: nil)
        guard let instance = storyboard.instantiateViewController(withIdentifier: "Identifier") as? BasicViewController else {
            return nil
        }
        object_setClass(instance, T.self)
        return instance as? T
    }

Optionals are added to avoid force unwrap (swiftlint warnings), but method returns correct objects.

Also: you need to initialize properties existing only in subclass before reading them from casted objects (if subclass has those properties and BasicViewController does not). Those properties won't be initialized automatically and attempt to read them before initialization will lead to crash. Because they are there in effect of casting it's very likely that even weak variables won't be set to nil (will contain garbage).


Although it's not strictly a subclass, you can:

  1. option-drag the base class view controller in the Document Outline to make a copy
  2. Move the new view controller copy to a separate place on the storyboard
  3. Change Class to the subclass view controller in the Identity Inspector

Here's an example from a Bloc tutorial I wrote, subclassing ViewController with WhiskeyViewController:

animation of the above three steps

This allows you to create subclasses of view controller subclasses in the storyboard. You can then use instantiateViewControllerWithIdentifier: to create specific subclasses.

This approach is a bit inflexible: later modifications within the storyboard to the base class controller don't propagate to the subclass. If you have a lot of subclasses you may be better off with one of the other solutions, but this will do in a pinch.