OGeek|极客世界-中国程序员成长平台

标题: objective-c - iOS(重新)使用 NIB 作为模板 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:08
标题: objective-c - iOS(重新)使用 NIB 作为模板

我创建了一个具有不同 View 的 nib 文件。我打算使用这个 nib 文件作为模板,就像在 web(即 html)中一样。因此,创建此 nib 的新实例并用实际数据填充它,创建 nib 的另一个新实例并用实际数据填充等...

但是当我尝试这样做时,nib 实例的行为不同。只有一个被创建。我错过了什么吗? nib 文件不应该这样使用吗?

这是我尝试使用我的 nib 文件的方法 -

    int yCoord = 0;

    for(int i=0; i<[resultSet count]; i++)
    {
        [[NSBundle mainBundle] loadNibNamed"msgView" owner:self options:nil];
        UIView *tmpMsgView = [[UIView alloc] initWithFrame:CGRectMake(0, yCoord, msgView.view.frame.size.width, msgView.view.frame.size.height)];
        tmpMsgView         = msgView.view;

        UILabel *senderLabel = (UILabel *)[tmpMsgView viewWithTag:1];
        [senderLabel setText"trial"];

        [self.view addSubview:tmpMsgView];
        [tmpMsgView release];
        yCoord += msg.view.frame.size.height;

    }

这个 msgView 连接到 nib 文件(通过 IB)并且该 nib 文件的所有者也被定义为此 viewController类。



Best Answer-推荐答案


您的代码一遍又一遍地添加同一个实例,而不是每次都添加一个新实例。

UIView *testView = [[UIView alloc] init];
testView.backgroundColor = [UIColor blueColor];
for (int i=0; i<5; i++) {
    testView.frame = CGRectMake(0.0, (i+1)*40.0, 200.0, 20.0);
    [self.window addSubview:testView];
}
[testView release];

for (int i=0; i<5; i++) {
    UIView *testView = [[UIView alloc] init];
    testView.backgroundColor = [UIColor blueColor];
    testView.frame = CGRectMake(0.0, (i+1)*40.0, 200.0, 20.0);
    [self.window addSubview:testView];
    [testView release];
}

是两个非常不同的东西。 第一个实际上没有什么意义,并导致一个蓝色条, 第二个更有意义,结果是 5 个蓝条——我认为这就是你想要的。

看下面,它将创建 5 个不同颜色的矩形 - 这是为了说明每个矩形都是从 Nib 加载的单独实例:

for (int i=0; i<5; i++) {
    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed"aView" owner:self options:nil];        
    UIView *nibView = [nibObjects objectAtIndex:0];

    nibView.backgroundColor = [UIColor colorWithRedi+1)*0.14 greeni+1)*0.11 blue:200.0 alpha:1.0];
    nibView.frame = CGRectMake(0.0, (i+1)*40.0, 200.0, 20.0);
    [self.window addSubview:nibView];
}

现在,如果我们在循环之前只分配一次 nibObjects 数组,我们又会遇到同样的问题,因为我们一遍又一遍地添加相同的实例,这将导致只有一个矩形:

NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed"aView" owner:self options:nil];        
for (int i=0; i<5; i++) {
    UIView *nibView = [nibObjects objectAtIndex:0];

    nibView.backgroundColor = [UIColor colorWithRedi+1)*0.14 greeni+1)*0.11 blue:200.0 alpha:1.0];
    nibView.frame = CGRectMake(0.0, (i+1)*40.0, 200.0, 20.0);
    [self.window addSubview:nibView];
}

希望对你有帮助

关于objective-c - iOS(重新)使用 NIB 作为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7461032/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4