开发者

Is inheritance supported for view controllers and nibs

I am creating 2 view controllers and 2 nibs for each of the supported orientations of my app - portrait and landscape as recommended by apple.

The problem is that I am going to have loads of duplicated code - wi开发者_如何学运维ll inheritance work in interface builder?

i.e. can I declare a iboutlet label in a base class and use it for both of the nibs?

EDIT: I have 2 controllers, both inherit from a basecontroller. Can I have my IBactions and IBOutlets and arrays and tableview delegate code in the base and then link it from 2 different nibs? I am trying to get rid of some duplication


Q: can I declare a iboutlet label in a base class and use it for both of the nibs?

A: Yes it will work, use initWithNibName to initialize the controller with the desired Nib(xib).


I just posted here but I thought you could benefit from this as well.

I know this is an old thread, but I just found an incredibly blog post here.

Essentially, you have to iterate through all the views of the parent class and add them as subviews to your child class. Here's how I implemented it in my project:

// ChildViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addSubviewsFromSuperclass];  
}

// ParentViewController.h
- (void)addSubviewsFromSuperclass;   

// ParentViewController.m
- (void)addSubviewsFromSuperclass
{
    UIView *selfView = self.view;
    UIView *nibView = nil;
    @try
    {
        nibView = [NSBundle.mainBundle loadNibNamed:NSStringFromClass([self superclass]) owner:self options:nil][0];
    }
    @catch (NSException *exception)
    {
        NSLog(@"Something exceptional happened while loading nib:\n%@", exception);
    }
    self.view = selfView;
    for (UIView *view in nibView.subviews)
    {
        [self.view addSubview:view];
    }
}

That addSuviewsFromSuperclass method is not my coding. I have to give full credit to the author of the blogpost I mentioned above. Download his example project and you'll find it in his JMViewController.m.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜