iphone - 在循环中动态添加 UILabel

标签 iphone ios objective-c

我正在寻找将 UILabel 添加到 iPhone 上的 View 的函数或循环原型(prototype)。这样做的原因是我事先不知道我需要添加多少标签,因此需要动态添加它们。

我的伪代码如下。这个想法是给每个标签一个字符串,然后放在下一个屏幕中,因此是 +self.view.frame.size.width 语句。分页等工作完美,问题是所有标签似乎都在第二个屏幕上结束,即标签 3 出现在标签 2 的顶部。问题似乎是我总是引用 altLabel,因此一旦我移动到第二个位置,我一直在引用那个位置,并且从不移动到那里。

我可以使用“计数”变量来增加屏幕宽度,但如果这样做,每次更新标签文本时,它都会覆盖之前的内容。

int count = 0;
int maxNumber = 10;

    while(count < maxNumber) {
    //Add a label
        UILabel *altlabel; //Declare the label

        if (count > 0) {
            //Move the label
             altlabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(altlabel.frame)+self.view.frame.size.width,10,300,25)];
            altlabel.text = [NSString stringWithFormat:@"%@ %@ (%d)", _name,_age, class+count];
        }

        else {
             altlabel = [[UILabel alloc] initWithFrame:CGRectMake(10,10,300,25)];
            altlabel.text = [NSString stringWithFormat:@"%@ %@ (%d)", _name,_age, class];
        }


    altlabel.textColor = [UIColor greenColor];
    [altlabel sizeToFit];
    [_scrollView addSubview:altlabel];
        count++;
    }

最佳答案

问题是这一行:

UILabel *altlabel; // Declare the label

if (count > 0) {
    //Move the label
    altlabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(altlabel.frame)+self.view.frame.size.width,10,300,25)];
    altlabel.text = [NSString stringWithFormat:@"%@ %@ (%d)", _name,_age, class+count];
}

您正在使用 altlabel.frame 设置框架,但是没有设置 altlabel:您在第一行用 UILabel *altlabel 重新声明了它.

使用此代码,除第一个标签外,每个标签都将具有相同的框架。试试这个:

int count = 0;
int maxNumber = 10;

CGRect rect;

while(count < maxNumber) {
    // Add a label
    UILabel *altlabel; // Declare the label

    if (count > 0) {
        //Move the label
        altlabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(rect.frame)+self.view.frame.size.width*count, 10, 300, 25)];
        altlabel.text = [NSString stringWithFormat:@"%@ %@ (%d)", _name,_age, class+count];

    } else {
        altlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 25)];
        altlabel.text = [NSString stringWithFormat:@"%@ %@ (%d)", _name,_age, class];
    }

    rect = altlabel.frame;

    altlabel.textColor = [UIColor greenColor];
    [altlabel sizeToFit];
    [_scrollView addSubview:altlabel];
    count++;
}

现在新标签的框架保存在一个临时变量(CGRect 框架)中,您可以使用它。

关于iphone - 在循环中动态添加 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19220109/

相关文章:

iphone - 使用mapkit计算半径(以米为单位)

iphone - 在屏幕顶部显示文本字段的键盘

ios - Twitter OAuth 1 POST 请求不起作用

ios - iPad 普通话翻译 API

iphone - 如何在横向模式下转换 Navigation Bar 和 Navigation Controller

iphone - iOS自定义UIButton

iPhone/iPad 应用程序开发 TV Out

iphone - Cocos2d for iPhone 与 Cocos2d-x

ios - 如何修改Unity自动生成的xCode项目?

ios - 如果应用是通过触摸推送启动的,有没有办法等待应用的主页面完成加载后运行代码?