Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an XIB?

Tags:

iphone

sdk

xib

I have an app with 2 screens (MainViewController and AboutViewController). Upon the user clicking a button, I'd like to load the AboutViewController screen, which is defined in another XIB.

Seems simple, but I can't seem to find my google-fu today. How do I pull this off?

like image 738
AngryHacker Avatar asked Sep 19 '09 09:09

AngryHacker


People also ask

How do I load a controller from XIB Swift?

Once you decided on a type of UI Controller (View, TableView, CollectionView, etc.), go into File > New > File (⌘N) and select Cocoa Touch Class . Click next. Now we are going to select the subclass and give the new UI Element a name. Let's call it RateMe, with the type of UIViewController .


2 Answers

When you call [AboutViewController init], it's expected to call some form of [super init], which is a synonym for [UIViewController init]. When this happens, your view controller will automatically look for a nib file called (in your case) AboutViewController.xib. If it finds that file, it loads it's contents into your view controller for you.

So basically, all you need to do is initialize your view controller, and make sure it has the same name as the associated nib file.

If you wanted to load a nib file with a different name into your view controller, you could explicitly call initWithNibName:bundle: with the name of whichever nib file you like.

If the standard init (with a same-name nib file) isn't working for you, there are a couple things you could check.

  • the spelling of the class name is the same as the spelling (and case) of the nib file
  • the nib file is included in the project, and not just sitting in the same directory
  • your UIViewController subclass's init method does also call [super init]
  • you are calling your UIViewController subclass's init method
  • you are indeed making your view controller's view visible
like image 146
Tyler Avatar answered Oct 15 '22 15:10

Tyler


With an About screen you probably just want to show a view and then dismiss it. So rather than use a whole new view controller you can just cover the current view.

Assuming you have an ivar

UIView *aboutUsView;

with the appropriate property.

In your view controller do:

[[NSBundle mainBundle] loadNibNamed:@"AboutUsView" owner:self options:nil]; // Retains top level items
[self.view addSubview:aboutUsView];  // Retains the view
[aboutUsView release];

To remove the view, say in an action connected to a button on the view, do:

[aboutUsView removeFromSuperview], aboutUsView = nil;  // Releases the view
like image 21
Steve Weller Avatar answered Oct 15 '22 16:10

Steve Weller