xcode 如何设置一半屏幕高度的视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30456708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:12:11  来源:igfitidea点击:

How to setup a view with a half of screen height?

iosxcodeswiftautolayout

提问by Hieu Duc Pham

I want to set view1's height to half of the screen's height for all devices (when the device in the portrait mode)

我想将所有设备的view1的高度设置为屏幕高度的一半(当设备处于纵向模式时)

Here is what I want it to look like:

这是我想要的样子:

enter image description here

在此处输入图片说明

so I make an auto layout of View1's height

所以我对 View1 的高度进行了自动布局

    @IBOutlet weak var heighConstraint: NSLayoutConstraint!

my viewwillappear function here:

我的 viewwillappear 功能在这里:

override func viewWillAppear(animated: Bool) {
        self. heighConstraint.constant = self.view.frame.size.height / 2
}

But it's not worked when I ran my app. what's wrong in here?

但是当我运行我的应用程序时它不起作用。这里有什么问题?

回答by Jen Jose

I know the accepted answer is correct but there is simpler method to do so -

我知道接受的答案是正确的,但有更简单的方法 -

Add the view (the one shown in yellow color). Pin it to three edges (top, leading and trailing). I have set it as 0 but change it as per your need.

添加视图(以黄色显示的视图)。将其固定到三个边缘(顶部、前导和尾部)。我已将其设置为 0,但根据您的需要进行更改。

enter image description here

在此处输入图片说明

Create Height Equal to constraint to main View as

创建高度等于主视图的约束为

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

Open that Constraint in the Inspector view and edit the multiplier as 0.5. Setting it as 0.5 takes the height value of half the height of mainView.

在 Inspector 视图中打开该约束并将乘数编辑为 0.5。将其设置为 0.5 的高度值是 mainView 高度的一半。

enter image description here

在此处输入图片说明

Just make sure FirstItem = View1 and SecondItem = SuperView as shown in the image.

只需确保 FirstItem = View1 和 SecondItem = SuperView,如图所示。

回答by tounaobun

Try to change heightConstraint's constant value in viewDidLayoutSubviewsmethod.

尝试heightConstraintviewDidLayoutSubviews方法中更改的常量值。

override func viewDidLayoutSubviews() {
    heightConstraint.constant = self.view.frame.size.height / 2
}

回答by IRAVIPATEL

Please try this out. Hope it will help you out. The below line will take the bounds of the device and will set the frame or height according to it.

请试试这个。希望它能帮到你。下面的行将获取设备的边界,并根据它设置框架或高度。

view1.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/2);

Hope this helps!!! Good Luck...

希望这可以帮助!!!祝你好运...