Correct way to load a Nib for a UIView subclass
MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]
I'm using this to initialise the reusable custom views I have.
Note that you can use "firstObject" at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.
Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;}
Normally, in the TopArea.xib
, you would click on File Owner and set the file owner to YourClass. Then actually in YourClass.h you would have IBOutlet properties. In TopArea.xib
, you can drag controls to those outlets.
Don't forget that in TopArea.xib
, you may have to click on the View itself and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)
If you want to keep your CustomView
and its xib
independent of File's Owner
, then follow these steps
- Leave the
File's Owner
field empty. - Click on actual view in
xib
file of yourCustomView
and set itsCustom Class
asCustomView
(name of your custom view class) - Add
IBOutlet
in.h
file of your custom view. - In
.xib
file of your custom view, click on view and go inConnection Inspector
. Here you will all your IBOutlets which you define in.h
file - Connect them with their respective view.
in .m
file of your CustomView
class, override the init
method as follow
-(CustomView *) init{ CustomView *result = nil; NSArray* elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options: nil]; for (id anObject in elements) { if ([anObject isKindOfClass:[self class]]) { result = anObject; break; } } return result;}
Now when you want to load your CustomView
, use the following line of code[[CustomView alloc] init];
Follow the following steps
- Create a class named MyView .h/.m of type
UIView
. - Create a xib of same name
MyView.xib
. - Now change the File Owner class to
UIViewController
fromNSObject
in xib. See the image below Connect the File Owner View to your View. See the image below
Change the class of your View to
MyView
. Same as 3.- Place controls create IBOutlets.
Here is the code to load the View:
UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];MyView* view=(MyView*)controller.view;[self.view addSubview:myview];
Hope it helps.
Clarification:
UIViewController
is used to load your xib and the View which the UIViewController
has is actually MyView
which you have assigned in the MyView xib..
DemoI have made a demo grab here