Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a UIView from a NIB?

I have been using UIViewControllers and initWithNibName with much success, basically using them as a convenient way to design the view with Interface Builder. Unfortunately I have built a hierarchy of views before noticing this line in the UIViewController documentation:

Note: You should not use view controllers to manage views that fill only a part of their window

My question is this: Having a very simple NIB that only has a UIView in addition to the default First Responder and Owning Object, what is the simplest way to load the UIView into my code?

I have not been able to get loadNibNamed:owner:options: to work at this point, but suspect the answer will involve it somehow.

like image 583
Winder Avatar asked Apr 15 '10 19:04

Winder


People also ask

How do you load a nib on a storyBoard?

If you want to load the view from a nib in code you would just instantiate it directly using the same technique. All the subclass does is take the code to instantiate the view from a nib and put it in a hook for the storyboard to use.

How do I install UIView?

Open Xcode ▸ File ▸ New ▸ File ▸ Cocoa Touch class ▸ Add your class name ▸ Select UIView or subclass of UIView under Subclass of ▸ Select language ▸ Next ▸ Select target ▸ Create the source file under your project directory. Programatically create subviews, layout and design your custom view as per requirement.


1 Answers

Yes, just call

[[NSBundle mainBundle] loadNibNamed:@"viewNib" owner:self options:nil];

You normally do this from the view controller you have set as File's Owner in the NIB. That way, you can declare an outlet for the view in the view controller which will automatically get connected when you load the NIB file. You don't even have to work with the return value of the method in this case.

like image 57
Ole Begemann Avatar answered Oct 09 '22 16:10

Ole Begemann