iOS:如何使用XIB以编程方式创建视图,但不使用View Controller

时间:2012-08-31 05:11:07

标签: objective-c ios

我正在尝试使用一些相同的子视图填充滚动视图,但数据更改除外。如果我想以编程方式完成整个事情,我可以这样:

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];
}

一切都好。现在,如果我的subView有点复杂,我该如何做同样的事情,我想用Interface Builder和xib存档来解决它?到目前为止,我有:

  • 创建了我自己的自定义视图代码,ItemSubview,使用IBOutlet NSString扩展UIView * dataLabel
  • 创建了我的xib文件,将文件的所有者设置为ItemSubview类,并将我的标签连接到插座

然后,在代码中:

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];
}

当我这样做时,我的itemSubview被绘制(我可以看到itemSubview的背景颜色),但不是xib存档中的dataLabel。我错过了什么/不理解?为什么这是以编程方式工作,而不是使用xib文件?

1 个答案:

答案 0 :(得分:8)

这样做:

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

确保在xib文件中,顶级视图是ItemSubview类,并且dataLabel正确连接到ItemSubview的插座。文件的所有者应留空。