Reputation: 36243
Is it possible to implement initWithNubName for a custom class that extends UIView.
Example:
.h
@interface UIPullerView : UIView
{
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
.m
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
NSBundle *bundle = nibBundleOrNil==nil ? [NSBundle mainBundle] : nibBundleOrNil;
NSString *nibName = nibNameOrNil==nil ? @"UIPullerView" : nibNameOrNil;
if (self == [[bundle loadNibNamed:nibName owner:self options:nil] objectAtIndex:0])
{
NSLog(@"yes, the same class");
}
return self;
}
some controller class calls this
UIPullerView *puller = [[UIPullerView alloc] initWithNibName:nil bundle:nil];
This is not a working example because I don't set the first XIB object to self. If I would I would loos a reference to the main class right? So I would like to add a method that would read XIB file and replicate the object from XIB into self. I don't want to use UIViewController but the UIView so no additional views should be added to main view.
Se also how I set the XIB:
I would do
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
...
self = [[bundle loadNibNamed:nibName owner:self options:nil] objectAtIndex:0]
return self;
}
but this isn't right true?
Is that possible?
Upvotes: 3
Views: 8204
Reputation: 51
Try this:
- (instancetype)initWithNib {
NSString *nibName = [NSString stringWithUTF8String:object_getClassName(self)];
return [[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil] objectAtIndex:0];
}
Upvotes: 0
Reputation: 51911
Create a ExampleView.xib
Create ExampleView.h
and ExampleView.m
@interface ExampleView : UIView
@end
In the ExampleView.xib
's Identity Inspector, set Custom Class to ExampleView
In Example.m
, add awakeFromNib
- (void)awakeFromNib
{
[super awakeFromNib];
// [self whateverInits];
}
which will be executed whenever the view is loaded, say, by:
NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@"ExampleView" owner:self options:nil];
ExampleView *exampleView = [objects firstObject];
Upvotes: 1
Reputation: 3038
To get around the issue of assigning self and losing the main class reference, I wonder if you should do it similarly as with loading a UITableViewCell
from a NIB:
[[NSBundle mainBundle] loadNibNamed:@"MyTableCell" owner:self options:nil];
cell = myTableCell;
self.myTableCell = nil;
and set the class that is doing this as the owner of the NIB.
Of course, if you're instantiating your UIPullerView
in multiple, different, places then that last part gets tricky...
Upvotes: 3