meriial
meriial

Reputation: 5136

iOS: how to create views programatically using XIB, but without using View Controller

I am trying to fill a scroll view with a number of subviews that are identical, except the data changes. If I want to do the whole thing programatically, I can, like so:

int width = 110;
int count = 0;
self.scrollView.contentSize=CGSizeMake(width*[items count],100);

for (NSString *id in items) {
    Item *item = [items objectForKey:id];
    CGRect frame = CGRectMake(count*width, 0, 100, 100);
    UIView *itemSubview = [[UIView alloc] initWithFrame:frame];

    CGRect dataLabelFrame = CGRectMake( 0, 52, 35, 30 );
    UILabel* dataLabel = [[UILabel alloc] initWithFrame: dataLabelFrame];
    dataLabel.text = @"Data specific to item"; // item.property or something
    dataLabel.font:[UIFont systemFontOfSize:30];
    dataLabel.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];

    [itemSubview addSubview:dataLabel];
    [self.scrollView addSubview:itemSubview];
    [itemSubview release];
}

All good. Now, how do I do the same thing if my subView is a little more complex, and I want to lay it out with Interface Builder and a xib archive? So far I have:

then, in code:

int width = 110;
int count = 0;
self.scrollView.contentSize=CGSizeMake(width*[items count],100);

for (NSString *id in items) {
    Item *item = [items objectForKey:id];
    CGRect frame = CGRectMake(count*width, 0, 100, 100);
    ItemSubview *itemSubview = [[ItemSubview alloc] initWithFrame:frame];
    [itemSubview setBackgroundColor:[UIColor colorWithRed:0.0 green:0.2 blue:0.0 alpha:0.2]]; // to see where it ends up

    [[NSBundle mainBundle] loadNibNamed:@"ItemSubview" owner:itemSubview options:nil];
    itemSubview.dataLabel.text = @"Data specific to item"; // item.property or something
    [self.scrollView addSubview:itemSubview];
    [itemSubview release];
}

When I do this, my itemSubview gets drawn (I can see the background color of the itemSubview), but not the dataLabel that was in the xib archive. What am I missing/not understanding? Why does this work programatically, but not with a xib file?

Upvotes: 7

Views: 5470

Answers (1)

Darren
Darren

Reputation: 10129

Do it like this:

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ItemSubview" owner:self options:nil];
    ItemSubview *itemSubview = [topLevelObjects objectAtIndex:0];

Make sure that in your xib file, the top level view is of class ItemSubview, and that dataLabel is properly hooked up to ItemSubview's outlet. File's owner should be left blank.

Upvotes: 8

Related Questions