只显示最后一个标签

问题描述:

在下面的代码中,我打算以可编程方式在视图的每一行中以编程方式添加两个标签。 “标签”被添加到视图中,但没有问题,但“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 

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

+0

你说的话很有道理。所以我将语句更改为以下内容:[scrollView addSubview:[infoLabels objectAtIndex:[infoLabels count] -1]]; //将Label添加为子视图。 infoLabels在界面中定义,就像标签一样。仍然是同样的问题。 – saman01

+0

对不起,我明白了。让我尝试。 – saman01