iOS两个视图覆盖父视图的一半 [英] iOS two views cover exactly half of parent view
问题描述
在我的应用程式中,我要实现这种布局:
因此,父视图包含两个子视图。第一个开始正好在中间(高度/ 2),第二个开始在父视图的中间。我发现这是不可能的,在IB中的约束。所以我在 viewDidLoad
方法中使用这个代码:
NSLayoutConstraint * constraint = [NSLayoutConstraint constraintWithItem:firstView
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0] ;
[self.view addConstraint:constraint];
现在可以使用,但只有当应用程序在iPhone上运行时。因为视图的大小是像iPhone屏幕。如果这个应用程序运行在iPad上,有一个问题,因为屏幕有不同的大小,所以这个父视图更长。约束(上面的代码)仍然需要来自IB的视图大小的0.5 *大小,而不是从视图的iPad大小。
结果是此视图具有相同的大小。
$ toItem:self.view
在iPad中像在iPhone。在iPad中有一个大的空格,然后有一个视图与iPhone的大小。 你能告诉我要做什么,使其通用的各种屏幕尺寸?非常感谢
确定,所以我只是想出了如何做到这一点。只需将代码放入 viewDidLayoutSubviews
方法中,而不是 viewDidLoad
。我在主题中找到的解决方案无法在viewDidAppear之前正确设置框架 。
这是我的代码:
[subView1 setFrame:CGRectMake (0,0,self.view.frame.size.width,self.view.frame.size.height / 2)];
[subView2 setFrame:CGRectMake(0,self.view.frame.size.height / 2,self.view.frame.size.width,self.view.frame.size.height / 2)];
感谢所有人的努力!
In my app I want to achieve this layout:
So parent view contains two sub views. First one ends exactly in a middle (height / 2) and second starts in a middle of parent view. I have found out that it is impossible to do that in the IB with constraints. So I used this code in viewDidLoad
method:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:firstView
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0];
[self.view addConstraint:constraint];
Now it works but only if the app runs on the iPhone. Because size of the view is like iPhone screen. If this app runs on the iPad, there is a problem because screen has different size so this parent view is longer. And constraint (code above) still takes 0.5 * size of the views size from the IB and not size from the iPad size of the view. Item toItem:self.view
still takes size from the IB.
Result is that this view has a same size in the iPad as in the iPhone. In the iPad there is a large blank space and then there is a view with iPhone size.
Can you tell what I have to do to make it universal for various screen sizes? Thank you very much
OK so I just figured out how to do this. Simply put the code into viewDidLayoutSubviews
method and not to viewDidLoad
. The solution I found in the topic Unable to set frame correctly before viewDidAppear.
Here is my code:
[subView1 setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2)];
[subView2 setFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, self.view.frame.size.height / 2)];
Thanks to all for effort!
这篇关于iOS两个视图覆盖父视图的一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!