Reputation: 355
My iOS app has a root view controller, and I want to add a few custom UIView
to it in runtime. I call these custom views widgets because they are small and basically pretty same except size, label text etc.
I have created .h and .m for my widgets, and .xib file. In my root view controller viewDidLoad
I do this:
TestMyView *cell = [[[NSBundle mainBundle] loadNibNamed:@"TestMyView" owner:self options:nil] objectAtIndex:0];
[self.view addSubview: cell];
It works fine. However, I still can't figure out:
"[<TestViewController 0x7517210> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key mylabel"
if I add UILabel
mylabel as IBOutlet to my custom UIView class .h file. (I drag drop UILabel in IB then control-drag to .h) I need to change label text when view is created. And I dont quite understand why it complains TestViewController while I didn't add IBOutlet to it, but my custom view .h class?If you think I suck at explain this, here's my project code: https://dl.dropbox.com/u/43017476/custom.tar.gz
Upvotes: 2
Views: 5199
Reputation: 7717
You're close. A few notes.
1st - when you load the view from the nip, the "owner" is the class which has the properties (IBOutlets) references by the nib. That will probably be an instance of TestMyView. Usually, create the custom view and let it load it's own nib (as illustrated below).
2nd - loadNibNamed returns an NSARRAY, not a UIVIEW; so you'll want to pull your view out of the array.
Here's an example of creating your custom view (widget):
CGRect frame = CGRectMake(nextLeft, nextTop, tileWidth, tileHeight);
TestMyView *widget = [[TestMyView alloc] initWithFrame:frame andFoo:foo];
[widget setWidgetTappedBlock:^{
// handle tap for this widget
}];
[self.widgetContainerView addSubview:widget];
This is part of your custom views implemenatation:
@implementation TestMyView
- (id)initWithFrame:(CGRect)frame andFoo:(Foo *)foo
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor clearColor]];
NSArray *nibObjects=[[NSBundle mainBundle] loadNibNamed:@"TestMyView" owner:self options:nil];
[self addSubview:[nibObjects objectAtIndex:0]];
// More initialization code
}
return self;
}
@end
And the interface:
@interface ProductTileView : UIView
@property (nonatomic, weak) IBOutlet UIView *view;
@property (nonatomic, copy) ProductTappedBlock widgetTappedBlock;
- (id)initWithFrame:(CGRect)frame andFoo:(Foo *)foo;
@end
Edit: PS In your example, the error is caused because the owner sent to loadNib is 'self', which is your view controller. Your view controller doesn't have the 'myLabel' property, your custom view does.
Upvotes: 4
Reputation: 2918
I think you have to initiate them befor adding to your rootView!
TestMyView *cell = [[TestMyView alloc]initWithNibName:@"TestMyView" bundle:[NSBundle mainBundle]];
[self.view addSubview: cell];
Upvotes: 0