ios - 自动布局程序化纵横比设置
问题描述
我正在尝试添加一个子视图来查看和定义自动布局约束,包括纵横比。但是我在运行时看到的纵横比并不是我在约束中定义的。我究竟做错了什么?正如您在代码中看到的,背景视图高度应该是背景视图宽度的 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
}
}
这是屏幕截图:
解决方案
“背景视图高度应为背景视图宽度的 0.5”
您的屏幕截图大小是1334 x 750
你的backgroundView
- 包括边界 - 是1334 x 667
1334 * 0.5 == 667
所以,你得到的正是你所要求的。
推荐阅读
- arrays - 将两个不同的项目视为一个独特的项目的有效方法?
- django - 如何在基于类的视图中调用和使用我在 url 中给出的 pk?
- scala - 如何禁用 IntelliJ 的基于缩进的大括号处理?
- javascript - CSS在移动视图中搞砸了
- python-3.x - 无法理解 DataFrame 方法“loc”逻辑,如果我们使用不正确的标签名称
- c# - 为什么 Autofac.Integration.WebApi.Owin 5.0.0 在 TargetFramework v4.7.1 上引用 System.Net.Http 4.2.0?
- angular - 激活组件时重置组件变量
- python - 如何使“FileHandler”从日志消息中去除终端转义序列(颜色)?
- powershell - 有没有一种简单的方法可以输出到 xlsx?
- json - Jolt Transformation 将值放入错误的数组元素中