如何在Xcode中以编程方式添加多个UILabel?

时间:2014-07-15 00:29:29

标签: ios objective-c uilabel

Xcode中的Hello我试图以编程方式向我的图像添加两个标签但是当我添加第二个标签时它将覆盖我的第一个。这是我的代码:

    //first label
    UILabel* caption = [[UILabel alloc] initWithFrame:
                        CGRectMake(-25, 0, 320, 50)
                        ];
    caption.backgroundColor = [UIColor whiteColor];
    caption.textColor = [UIColor blackColor];
    caption.textAlignment = UITextAlignmentLeft;
    caption.font = [UIFont systemFontOfSize:16];
    caption.text = [NSString stringWithFormat:@"  @%@",[data objectForKey:@"username"]];
    [self addSubview: caption];

    //second label
    UILabel* bottomBox = [[UILabel alloc] initWithFrame:
                        CGRectMake(-25, -200, 320, 50)
                        ];
    caption.backgroundColor = [UIColor whiteColor];
    caption.textColor = [UIColor blackColor];
    caption.textAlignment = UITextAlignmentCenter;
    caption.font = [UIFont systemFontOfSize:16];
    caption.text = [NSString stringWithFormat:@"  Testing"];
    [self addSubview: bottomBox];

我已经尝试将" 0改为-200来修改Y坐标,这样第二个标签就会向下移动但是由于某种原因它只会覆盖第一个标签。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

第二个标签的所有代码都引用第一个变量caption而不是bottomBox。你想要:

//second label
UILabel* bottomBox = [[UILabel alloc] initWithFrame:CGRectMake(20, 200, 320, 50)];
bottomBox.backgroundColor = [UIColor whiteColor];
bottomBox.textColor = [UIColor blackColor];
bottomBox.textAlignment = UITextAlignmentCenter;
bottomBox.font = [UIFont systemFontOfSize:16];
bottomBox.text = @"Testing";
[self addSubview: bottomBox];