Michael Eilers Smith
Michael Eilers Smith

Reputation: 8618

Centering UI elements in middle of screen programmatically

I'm trying to do something fairly simple, but just can't manage to make it happen. I have an UIImage followed by two UILabels, each on on top of the other, that I want to center in the middle of a UIView.

(empty space)
   UIImage
   UILabel
   UILabel
(empty space)

This is what I have so far:

UIView* baseView = [[UIView alloc] initWithFrame:CGRectMake(0,0,[[UIScreen mainScreen] applicationFrame].size.width,[[UIScreen mainScreen] applicationFrame].size.height)];
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 50)];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 50)];

[imageView setCenter:CGPointMake(baseView.frame.size.width / 2, baseView.frame.size.height / 2)];
[label1 setCenter:CGPointMake(baseView.frame.size.width / 2, baseView.frame.size.height / 2)];
[label2 setCenter:CGPointMake(baseView.frame.size.width / 2, baseView.frame.size.height / 2)];

[baseView addSubview:imageView];
[baseView addSubview:label1];
[baseView addSubview:label2];
[self addSubview:baseView];

But it doesn't seem to be working. All the elements are over each other. Any ideas?

Upvotes: 0

Views: 396

Answers (1)

KudoCC
KudoCC

Reputation: 6952

Have it a try.

I add an container view to hold the imageView and the two labels, then center the container view in baseView. Set backgroundColor of container to clear color so we can't see it.

UIView* baseView = [[UIView alloc] initWithFrame:CGRectMake(0,0,[[UIScreen mainScreen] applicationFrame].size.width,[[UIScreen mainScreen] applicationFrame].size.height)];
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 50)];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 50)];

UIView * container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 175+50+50)] ;
container.backgroundColor = [UIColor clearColor] ;

[imageView setCenter:CGPointMake(container.bounds.size.width/2, imageView.bounds.size.height/2)];
[label1 setCenter:CGPointMake(imageView.center.x, imageView.bounds.size.height + label1.bounds.size.height / 2)];
[label2 setCenter:CGPointMake(imageView.center.x, label1.frame.origin.y + label1.bounds.size.height + label2.bounds.size.height / 2)];

container.center = CGPointMake(baseView.bounds.size.width/2, baseView.bounds.size.height/2) ;

[container addSubview:imageView];
[container addSubview:label1];
[container addSubview:label2];

[baseView addSubview:container] ;

[self addSubview:baseView];

Upvotes: 1

Related Questions