Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single UIViewcontroller, how to switch among multiple xibs?

I have a subclass of UIViewController:

 @interface KBViewController : UIViewController

with multiple xibs, for example, one is a Qwerty and the another is Dvorak layout:

 KBViewControllerQuerty~iphone.xib
 KBViewControllerDvorak~iphone.xib

So when the user click a button, Qwerty is switch to Dvorak. As you may see, the code logic is identical for both keyboard layouts. What I need is to reload the view with another xib.

Hopefully, all the buttons in the Dvorak xib will be hooks to the responding IBOutlets in KBViewController.

What is the right way to switch between the two xibs?

like image 837
ohho Avatar asked Jan 24 '13 08:01

ohho


1 Answers

All Nibs has the designated File's Owner. IBOutlet and IBAction linking is done based upon the File's Owner. So you could define a view controller and two Nibs, with each Nib file's File's Owner set to the defined view controller.

That is, if you set File's Owner of all KBViewController*.xib files to KBViewController and have a KBViewController object somewhere you could load the KBViewController*.xib you want by initWithNibNamed method (recreate the view controller)

If you should maintain the same KBViewController object all along, you could create a KBViewController object without Nib. In KBViewController.m, implement loadView and manually load the UIView object with -[NSBundle loadNibNamed] method (load and change self.view programmatically).

UIView *someView = [[[NSBundle mainBundle] loadNibNamed:@"SomeNibFile"
                                                  owner:self
                                                options:nil] objectAtIndex:0];
self.view = someView;

Note owner:self in above code. It must match with File's Owner of the @"SomeNibFile".

To change already loaded view:

id superview = self.view.superview;
[self.view removeFromSuperview];
UIView *someView = [[[NSBundle mainBundle] loadNibNamed:@"SomeNibFile"
                                                  owner:self
                                                options:nil] objectAtIndex:0];
self.view = someView;
[superview addSubview:self.view];

More detailed explanation: Resource Programming Guide - Loading Nib Files Programmatically

like image 177
9dan Avatar answered Oct 28 '22 13:10

9dan