When I use loadNibNamed
method to load a xib
file, how to pass some parameter?
[NSBundle loadNibNamed:xibName owner:[NSApplication sharedApplication]];
When I use loadNibNamed
method to load a xib
file, how to pass some parameter?
[NSBundle loadNibNamed:xibName owner:[NSApplication sharedApplication]];
In order to pass parameters when instantiating your class, add a wrapper to the
loadNibNamed:owner:
method and pass your parameters to this wrapper.
Here is the code snippet for this:
(ClassName *) GetInstanceWithParameter1:(ParameterType *)param1 andParameter2:(ParameterType *)param2 { ClassName *instance = [[ClassName alloc] initWithNibNamed:nibName bundle:nibBundle]; instance -> P1 = param1; instance -> P2 = param2; return instance; }
Here P1 and P2 are your class level variable corresponding to param1 and param2. Now you can use them anywhere in the code.
This is an example of something I did which worked for me.
Say you have a Xib (Nib) file (MyNibView.xib) which is a UIView.
That UIView has a Class linked to it, called NibView, which has a header and a main file; NibView.h and NibView.h.
If you don't know how to link a class to a Nib:
Click on your Nib > go to Identity Inspector > enter your Class under Custom Class > Class.
1) In NibView.h make sure you have the object (that you want to pass through) instantiated. For this example I will use a NSString called name.
@property NSString *name;
2) In NibView.m create a function (e.g. helloWorld) and in that function do whatever you want to do with the passed in object.
- (void) helloWorld {
NSLog(@"hello %@",self.name);
}
3) Write that method is NibView.h too
@property NSString *name;
- (void) helloWorld;
4) In the Class where you are passing data from (could be a ViewController for example), import your View Class
#import "NibView.h"
And write this code:
NSArray *nib =[[NSBundle mainBundle]loadNibNamed:@"MyNibView" owner:self options:nil];
// At this point - (void)awakeFromNib is called
NibView *view = [nib objectAtIndex:0];
view.name = @"Bob";
// Now lets call the method "helloWorld"
[view helloWorld];
// This line sets the MyNibView as the UIView of a ViewController (only relevant for this example).
self.view = view;
Hope this helps others like it helped me