首页 > 解决方案 > 自动布局程序化纵横比设置

问题描述

我正在尝试添加一个子视图来查看和定义自动布局约束,包括纵横比。但是我在运行时看到的纵横比并不是我在约束中定义的。我究竟做错了什么?正如您在代码中看到的,背景视图高度应该是背景视图宽度的 0.5,但在屏幕截图中并非如此。这是我的代码:

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
}


 }

这是屏幕截图:

在此处输入图像描述

标签: iosautolayoutuikitios-autolayout

解决方案


“背景视图高度应为背景视图宽度的 0.5”

您的屏幕截图大小是1334 x 750

你的backgroundView- 包括边界 - 是1334 x 667

1334 * 0.5 == 667

所以,你得到的正是你所要求的。


推荐阅读