7

データの変更を除いて、同じサブビューの数でスクロールビューを埋めようとしています。すべてをプログラムで実行したい場合は、次のようにできます。

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

すべて良い。さて、サブビューがもう少し複雑で、Interface Builderとxibアーカイブを使用してレイアウトしたい場合、同じことをどのように行うのですか?これまでのところ:

  • 独自のカスタムビューコードItemSubviewを作成し、IBOutlet NSString*dataLabelを使用してUIViewを拡張しました
  • 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ファイルでは機能しないのですか?

4

1 に答える 1

8

次のようにします。

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

xib ファイルで、最上位のビューが ItemSubview クラスであること、および dataLabel が ItemSubview のアウトレットに適切に接続されていることを確認してください。ファイルの所有者は空白のままにする必要があります。

于 2012-08-31T05:26:36.523 に答える