开发者

only the last label is displayed

In this following code I intend to programmatically add two labels in each row in a scrollable view. "label" gets added in the view with no problem but "infoLabel" I only see the last row. Has spent hours trying to figure out. Thanks for any help.

- (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 *i开发者_运维知识库nfoLabel = [[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


You are creating a single instance of infoLabel and resetting its frame on each iteration of the loop. If you intend to have multiple labels, you will have to allocate and initialize a label on each iteration on the loop. Make sure you relinquish the ownership of the label you are allocating after you add it as a subview.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜