以编程方式在屏幕中间居中UI元素

时间:2014-01-28 03:18:24

标签: ios iphone

我正在尝试做一些相当简单的事情,但却无法实现这一目标。我有一个UIImage后面跟着两个UILabel,每个UILabel都在另一个上面,我想把它放在UIView的中间。

(empty space)
   UIImage
   UILabel
   UILabel
(empty space)

这是我到目前为止所做的:

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

但它似乎没有起作用。所有元素都相互重叠。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

试一试。

我添加了一个容器视图来保存imageView和两个标签,然后将container视图置于baseView中心。设置container的backgroundColor以清除颜色,以便我们看不到它。

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