仅显示最后一个标签

时间:2011-07-27 18:41:15

标签: iphone objective-c xcode ipad

在下面的代码中,我打算以编程方式在可滚动视图的每一行中添加两个标签。 “label”在视图中添加没有问题,但“infoLabel”我只看到最后一行。 花了好几个小时试图找出答案。 谢谢你的帮助。

- (void)refreshList
{
    // remove all the labels from the GUI
    for (UILabel *label in scrollView.subviews)
        [label removeFromSuperview];
    RootModel *rm = [RootModel sharedModel];

    float labelOffset = LABEL_SPACING; // reset the spacing
    UILabel *infoLabel = [[UILabel alloc] init ];

    // repopulate the scroll view with Labels
    for (UILabel *label in labels)
    {
        NSLog(@"%@", label.text);
        CGRect labelFrame = label.frame; // fetch the frame of label

        labelFrame.origin.x = LEFT_LABEL_SPACING; // set the x-coordinate
        labelFrame.origin.y = labelOffset; // set the y-coordinate
        labelFrame.size.width = scrollView.frame.size.width/3;
        labelFrame.size.height = LABEL_HEIGHT; // set the height of Label
        label.frame = labelFrame; // assign the new frame to Label
        [scrollView addSubview:label]; // add Label as a subview

        CGRect infolabelFrame = infoLabel.frame; // fetch the frame of label

        infolabelFrame.origin.x = 10; // set the x-coordinate
        infolabelFrame.origin.y = labelOffset; // set the y-coordinate
        infolabelFrame.size.width = scrollView.frame.size.width/3;
        infolabelFrame.size.height = LABEL_HEIGHT; // set the height of Label
        infoLabel.frame = infolabelFrame; // assign the new frame to Label

        NSString *key = label.text;
        NSLog(@"%@", key);
        infoLabel.text = [rm.rLevels valueForKey:key];
        NSLog(@"%@    %@", infoLabel.text, key);

        infoLabel.frame = infolabelFrame; // fetch the frame of label
        [infoLabels addObject:infoLabel];
        [scrollView addSubview:infoLabel]; // add Label as a subview

        // increase the offset so the next button is added further down
        labelOffset += LABEL_HEIGHT + LABEL_SPACING;
    } // end for
} // end refreshList

1 个答案:

答案 0 :(得分:2)

您正在创建infoLabel的单个实例,并在循环的每次迭代中重置其frame。如果您打算拥有多个标签,则必须在循环的每次迭代中分配和初始化标签。在将其添加为子视图后,请确保放弃所分配标签的所有权。