user3807138
user3807138

Reputation: 13

How to add multiple UILabels programmatically in Xcode?

Hello in Xcode I am trying to add two labels to my image programmatically but when I add the second one it will overwrite my first one. Here is my code:

    //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];

I've tried changing the "0 to -200 to modify the Y coordinates so that the second label will shift down but it just overwrites the first one for some reason. Any help would be greatly appreciated thanks.

Upvotes: 1

Views: 1008

Answers (1)

rmaddy
rmaddy

Reputation: 318804

All the code for your 2nd label is referencing the 1st variable caption instead of bottomBox. You want:

//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];

Upvotes: 2

Related Questions