简体   繁体   English

自动布局编程纵横比设置

[英]Autolayout programmatic aspect ratio setting

I am trying to add a subview to view and define autolayout constraints, including aspect ratio.我正在尝试添加一个子视图来查看和定义自动布局约束,包括纵横比。 But aspect ratio that I see at runtime is not what I defined in constraints.但是我在运行时看到的纵横比不是我在约束中定义的。 What am I doing wrong?我究竟做错了什么? As you can see in code, background view height should be 0.5 of background view width, but that's not the case here in the screenshot.正如您在代码中看到的,背景视图高度应该是背景视图宽度的 0.5,但在屏幕截图中并非如此。 Here is my code:这是我的代码:

class ViewController: UIViewController {

private var backgroundView:UIView?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    view.backgroundColor = UIColor.orange

    backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
    backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1.0)
    backgroundView?.layer.borderColor = UIColor.white.cgColor
    backgroundView?.layer.borderWidth = 1.5
    backgroundView?.layer.cornerRadius = 4
    backgroundView?.clipsToBounds = true
    backgroundView?.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(backgroundView!)

    backgroundView?.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
    backgroundView?.heightAnchor.constraint(equalTo: backgroundView!.widthAnchor, multiplier: 0.5).isActive = true
    backgroundView?.centerXAnchor.constraint(equalTo: view!.centerXAnchor, constant: 0).isActive = true
    backgroundView?.topAnchor.constraint(equalTo: view!.topAnchor, constant: 4).isActive = true
}


 }

Here is the screenshot:这是屏幕截图:

在此处输入图片说明

"background view height should be 0.5 of background view width" “背景视图高度应该是背景视图宽度的 0.5”

Your screenshot size is 1334 x 750您的屏幕截图大小为1334 x 750

Your backgroundView - including the border - is 1334 x 667您的backgroundView - 包括边框 - 是1334 x 667

1334 * 0.5 == 667

So, you are getting exactly what you are asking for.所以,你得到的正是你所要求的。

Try to change height constraint to set:尝试更改高度约束以设置:

backgroundView?.heightAnchor.constraint(equalTo: view!.heightAnchor, multiplier: 0.5).isActive = true

NB: You are getting the exact result which you are looking for.注意:您正在获得您正在寻找的确切结果。 It has the height that's half of its width.它的高度是其宽度的一半。 There is nothing wrong with the screenshot.屏幕截图没有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM