How to use single storyboard uiviewcontroller for multiple subclass
Asked Answered
S

16

128

Let say I have a storyboard that contains UINavigationController as initial view controller. Its root view controller is subclass of UITableViewController, which is BasicViewController. It has IBAction which is connected to right navigation button of the navigation bar

From there I would like to use the storyboard as a template for other views without having to create additional storyboards. Say these views will have exactly the same interface but with root view controller of class SpecificViewController1 and SpecificViewController2 which are subclasses of BasicViewController.
Those 2 view controllers would have the same functionality and interface except for the IBAction method.
It would be like the following:

@interface BasicViewController : UITableViewController

@interface SpecificViewController1 : BasicViewController

@interface SpecificViewController2 : BasicViewController

Can I do something like that?
Can I just instantiate the storyboard of BasicViewController but have root view controller to subclass SpecificViewController1 and SpecificViewController2?

Thanks.

Soapy answered 1/1, 2013 at 15:15 Comment(4)
It might be worth pointing out that you can do this with nib. But if you're like me who want some nice features that only storyboard has (static/prototype cell, for example), then I guess we're out of luck.Fidele
#27337230Reinke
Does this answer your question? Cast to a subclass from StoryboardLeontine
10 yrs later, it's now trivial https://mcmap.net/q/175778/-cast-to-a-subclass-from-storyboardLeontine
A
60

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

Apheliotropic answered 1/1, 2013 at 17:51 Comment(8)
That was quick. As I thought, it would not be possible. Currently I come up with a solution by having just that BasicViewController class and have additional property to indicate which "class"/"mode" it will be acting as. Thanks anyway.Soapy
too bad :( Guess I have to copy and paste the same view controller and change its class as a workaround.Schaper
And this is why I don't like Storyboards ... somehow they are not really working once you do a bit more than standard views ...Koball
I'm spending some time trying to intercept the unarchiving process but so far I haven't been lucky. I tried to override classForKeyedUnarchiver on the parent UIViewController but this method is not called.Hello
There is another approach: Specify the custom logic in different delegates and in prepareForSegue, assign the correct delegate. This way, you create 1 UIViewController + 1 UIViewController in the Storyboard but you have multiple implementation versions.Menard
Thanks plam I've been thinking about this for a couple of days and that seems like the best solution. Storyboards don't really allow for proper subclassing and reusability in a general sense.Allaallah
Sorry, answer looks nice but seems that it isn't correct. Check my answer here: https://mcmap.net/q/174128/-how-to-use-single-storyboard-uiviewcontroller-for-multiple-subclassSignac
There actually is since iOS 13: instantiateViewController(identifier:creator:). See my answer.Humble
S
43

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
    }
}
Spatial answered 19/8, 2015 at 19:3 Comment(11)
Thanks, it just works, for example: class func instantiate() -> SubClass { let instance = (UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SuperClass") as? SuperClass)! object_setClass(instance, SubClass.self) return (instance as? SubClass)! }Sidwohl
I'm not sure I understand how's this supposed to work. The parent is setting its class as that of a child? How can you have multiple children then?!Vermiculation
Can you expand on how this is a solution? I agree with @user136265 -- how can you have multiple ChildVCs?Aciniform
OK guys, so let me just explain it little bit more in detail: What do we want to achieve? We want to subclass our ParentViewController so that we can use its Storyboard for more classes. So the magic line that does it all is highlighted in my solution and must be used in awakeFromNib in ParentVC. What happens then is that it uses all methods from newly set ChildVC1 which becomes as a subclass. If you want to use it for more ChildVCs? Simply do your logic in awakeFromNib .. if (type = a) { object_setClass(self, ChildVC1.self) } else { object_setClass(self.ChildVC2.self) } Good luck.Dominance
where is "type" being set? in user defined runtime attributes? or in code?Grazier
It is set in code in place where you call ParentVC from. Just set it as yours ParentVC variable attribute.Dominance
That doesn't awakeFromNib is called before the type is set. Likely need to move the type check login to viewDidLoad().Kraken
Also this doesn't seem to trigger viewDidLoad() in the subclass ChildVC2Kraken
Be very careful when using this! Normally this shouldn't be used at all... This simply changes the isa pointer of the given pointer and doesn't reallocate memory to accommodate for e.g. different properties. One indicator for this is that the pointer to self doesn't change. So inspection of the object (e.g. reading _ivar / property values) after object_setClass can cause crashes.Barleycorn
I tried this approach, from debugger I know that my subclass has been instantiated; but I cannot init the subclass' xib, getting a Thread1: BAD_ACCESS_EXC. Anyone else experienced this?Purify
Even design wise, I don't think we should be doing this since the parent has a semantic coupling with its children. It would be better just to ditch storyboard and use xibs instead.Accompany
S
16

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.

Site answered 19/3, 2015 at 14:18 Comment(1)
Surprisingly seems that this is possible with storyboards, thanks to ObjC runtime library. Check my answer here: https://mcmap.net/q/174128/-how-to-use-single-storyboard-uiviewcontroller-for-multiple-subclassSignac
H
9

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.

Homer answered 23/3, 2015 at 20:47 Comment(2)
We've done something similar in the project, but overriding the UIViewController's alloc method to get a subclass from an external class gathering the full info about all the overrides. Works perfectly.Ludovika
By the way this method may stop working as fas ar as Apple stops calling alloc on view controllers. For the example NSManagedObject class never receives alloc method. I think Apple could copy the code to another method: maybe +allocManagedObjectLudovika
S
7

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).

Signac answered 23/8, 2019 at 8:53 Comment(0)
E
6

try this, after instantiateViewControllerWithIdentifier.

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

like :

SubViewController *vc = [sb instantiateViewControllerWithIdentifier:@"MainViewController"];
[vc setClass:[SubViewController class]];
Ethnarch answered 4/2, 2017 at 1:56 Comment(3)
Please add some helpful explanation about what your code does.Metastasis
What happens with this, if you use instance variables from subclass? I'm guessing crash, because there is not enough memory allocated to fit that. In my tests, I've been getting EXC_BAD_ACCESS, so not recommending this.Preempt
This will not work if you will add new variables in child class. And child's init also will not be called. Such constraints makes all approach unusable.Freon
M
5

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.

Miso answered 22/3, 2015 at 3:25 Comment(5)
This isn't a subclass mate, this is just duplicating a ViewController.Kraken
That's not right. It becomes a subclass when you change Class to the subclass (step 3). Then you can make whatever changes you want to, and hook up to the outlets/actions in your subclass.Miso
I don't think you get the concept of subclassing.Kraken
If "later modifications within the storyboard to the base class controller don't propagate to the subclass", it's not called "subclassing". It's copy & paste.Guttery
The underlying class, selected in the Identity Inspector, is still a subclass. The object being initialized and controlling the business logic is still a subclass. Only the encoded view data, store as XML in the storyboard file and initialized via initWithCoder:, does not have an inherited relationship. This type of relationship is not supported by storyboard files.Miso
S
4

Objc_setclass method doesn't create an instance of childvc. But while popping out of childvc, deinit of childvc is being call. Since there is no memory allocated separetely for childvc, app crashes. Basecontroller has an instance , whereas child vc doesn't have.

Selfannihilation answered 21/5, 2017 at 18:14 Comment(0)
H
4

Here is a Swift solution which does not rely on Objective-C class swapping hacks. It uses instantiateViewController(identifier:creator:) (iOS 13+). I assume you have the view controller in a storyboard, with identifier template. The class assigned to the view controller in the storyboard should be the superclass:

let storyboard = UIStoryboard(name: "main", bundle: nil)

let viewController = storyboard.instantiateViewController(identifier: "template") { coder in 
    // The coder provides access to the storyboard data. 
    // We can now init the preferred UIViewController subclass.

    if useSubclass {
        return SpecialViewController(coder: coder)
    } else {
        return BaseViewController(coder: coder)
    }
}

Here is the documentation

Humble answered 7/7, 2022 at 15:58 Comment(0)
I
2

If you are not too reliant on storyboards, you can create a separate .xib file for the controller.

Set the appropriate File's Owner and outlets to the MainViewController and override init(nibName:bundle:) in the Main VC so that its children can access the same Nib and its outlets.

Your code should look like this:

class MainViewController: UIViewController {
    @IBOutlet weak var button: UIButton!

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: "MainViewController", bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        button.tintColor = .red
    }
}

And your Child VC will be able to reuse its parent's nib:

class ChildViewController: MainViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        button.tintColor = .blue
    }
}
Imperceptive answered 28/7, 2017 at 13:5 Comment(0)
L
2

There is a simple, obvious, everyday solution.

Simply put the existing storyboard/controller inside the new storyobard/controller. I.E. as a container view.

This is the exactly analogous concept to "subclassing", for, view controllers.

Everything works exactly as in a subclass.

Just as you commonly put a view subview inside another view, naturally you commonly put a view controller inside another view controller.

How else can could you do it?

It's a basic part of iOS, as simple as the concept "subview".

It's this easy ...

/*

Search screen is just a modification of our List screen.

*/

import UIKit

class Search: UIViewController {
    
    var list: List!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        list = (_sb("List") as! List
        addChild(list)
        view.addSubview(list.view)
        list.view.bindEdgesToSuperview()
        list.didMove(toParent: self)
    }
}

You now obviously have list to do whatever you want with

list.mode = .blah
list.tableview.reloadData()
list.heading = 'Search!'
list.searchBar.isHidden = false

etc etc.

Container views are "just like" subclassing in the same way that "subviews" are "just like" subclassing.

Of course obviously, you can't "sublcass a layout" - what would that even mean?

("Subclassing" relates to OO software and has no connection to "layouts".)

Obviously when you want to re-use a view, you just subview it inside another view.

When you want to re-use a controller layout, you just container view it inside another controller.

This is like the most basic mechanism of iOS!!


Note - for years now it's been trivial to dynamically load another view controller as a container view. Explained in the last section: https://mcmap.net/q/17273/-how-to-add-a-subview-that-has-its-own-uiviewcontroller-in-objective-c

Note - "_sb" is just an obvious macro we use to save typing,

func _sb(_ s: String)->UIViewController {
    // by convention, for a screen "SomeScreen.storyboard" the
    // storyboardID must be SomeScreenID
    return UIStoryboard(name: s, bundle: nil)
       .instantiateViewController(withIdentifier: s + "ID")
}
Leontine answered 7/10, 2019 at 16:27 Comment(0)
S
2

Thanks for @Jiří Zahálka's inspiring answer, I replied my solution 4 years ago here, but @Sayka suggested me to post it as an answer, so here it is.

In my projects, normally, if I'm using Storyboard for a UIViewController subclass, I always prepare a static method called instantiate() in that subclass, to create an instance from Storyboard easily. So for solve OP's question, if we want to share the same Storyboard for different subclasses, we can simply setClass() to that instance before returning it.

class func instantiate() -> SubClass {
    let instance = (UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SuperClass") as? SuperClass)!
    object_setClass(instance, SubClass.self)
    return (instance as? SubClass)!
}
Sidwohl answered 11/6, 2020 at 3:59 Comment(1)
I tried this and sometimes got Heap buffer overflows when I access attributes off the subclass. It seems like when you set the class this way the memory wasn't reassigned to the subclass properly, so I'm gonna say ....this method is probably not a good idea.Caird
A
1

Probably most flexible way is to use reusable views.

(Create a View in separate XIB file or Container view and add it to each subclass view controller scene in storyboard)

Appreciable answered 28/4, 2016 at 9:39 Comment(0)
L
1

Taking answers from here and there, I came up with this neat solution.

Create a parent view controller with this function.

class ParentViewController: UIViewController {


    func convert<T: ParentViewController>(to _: T.Type) {

        object_setClass(self, T.self)

    }

}

This allows the compiler to ensure that the child view controller inherits from the parent view controller.

Then whenever you want to segue to this controller using a sub class you can do:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    if let parentViewController = segue.destination as? ParentViewController {
        ParentViewController.convert(to: ChildViewController.self)
    }

}

The cool part is that you can add a storyboard reference to itself, and then keep calling the "next" child view controller.

Latex answered 11/4, 2019 at 20:19 Comment(0)
I
0

Cocoabob's comment from Jiří Zahálka answer helped me to get this solution and it worked well.

func openChildA() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil);
    let parentController = storyboard
        .instantiateViewController(withIdentifier: "ParentStoryboardID") 
        as! ParentClass;
    object_setClass(parentController, ChildA.self)
    self.present(parentController, animated: true, completion: nil);
}
Indices answered 9/6, 2020 at 20:28 Comment(0)
T
-1

It is plain simple. Just define the BaseViewController in a xib and then use it like this:

let baseVC: BaseViewController = BaseViewController(nibName: "BaseViewController", bundle: nil)
let subclassVC: ChildViewController = ChildViewController(nibName: "BaseViewController", bundle: nil)

To make is simple you can extract the identifier to a field and the loading to a method like:

public static var baseNibIdentifier: String {
    return "BaseViewController"
}

public static func loadFromBaseNib<T>() -> T where T : UIViewController {
    return T(nibName: self.baseNibIdentifier, bundle: nil)
}

Then you can use it like this:

let baseVC: BaseViewController = BaseViewController.loadFromBaseNib()
let subclassVC: ChildViewController = ChildViewController.loadFromBaseNib()
Tertiary answered 23/6, 2021 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.