Storyboarding UIViewController with multiple classes

I need one UIViewController in my storyboard, created by multiple classes. So I allow the "class" field to be empty in my storyboard (so what is the default UIViewController

?). Then I fill in the storyboard id " MyGenericView

".

Here are some classes:

@interface ClassA: UIViewController

@interface ClassB: UIViewController

      

MyGenericView

contains the whole prototype, I need to build my view in ClassA and ClassB. This is how I installed mine ClassA

:

ClassA *myClass = (ClassA*)[storyboard instantiateViewControllerWithIdentifier:@"MyGenericView"];

      

Finally, my view is shown in the app, but the code in mine is ClassA

never called. The object returned instantiateViewControllerWithIdentifier

is UIViewController

, the cast does not work.

I don't want to populate the "class" field with a class because I want to reuse this view for ClassB

. However, I don't want to duplicate this view in my storyboard.

I don't know if this seems clear to you, I apologize for my bad English :)

Thank!

+3


source to share


2 answers


I'm blowing up to find a solution to this question but the only thing that might work (I think) is to use delegates instead of subclassing.

I mean, you can implement 3 classes: ClassP, ClassC1, ClassC2; bind your storyboard to ClassP which implements the delegate protocol, then before the view (in prepearForSegue?) you can set a segue.destinationViewController delegate (of type P) to one of your classes ClassC1 or ClassC2 which explicitly implements the protocol.

Sample code for (not tested):

ClassP

@protocol ClassPDelegate <NSObject>

- (void)foo;

@end

@interface ClassP : UIViewController
...
@end

      



ClassC1 and ClassC2

#import "ClassP.h"
@property (nonatomic, weak) id <ClassPDelegate> delegate;

      

Caller class

...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"mySegue"])
    {
        ClassC1 *classC1 = [[ClassC1 alloc] init];
        [(ClassP *)segue.destinationViewController setDelegate:classC1];
    }
}
...

      

I hope this works! ps: I'm sorry, but your English is better than mine!

+4


source


What you want to do and what you might want to do is not always the same. Casting doesn't magically turn a UIViewController into a ClassA view controller. You need to change the class in the storyboard to ClassA or ClassB. You can copy and paste the view you created into as many other view controllers as you like. What's wrong with that?



-1


source







All Articles