【问题标题】:“Width equals height” constraint using visual format language使用视觉格式语言的“宽度等于高度”约束
【发布时间】:2017-12-01 13:40:26
【问题描述】:
为了添加宽度等于它的父视图高度,我们可以这样做
NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: view.superview, attribute: .height, multiplier: 1, constant: 0)
或者我们可以从界面生成器中完成
但是我怎样才能使用 VFL 做同样的事情呢?
【问题讨论】:
标签:
ios
autolayout
nslayoutconstraint
visual-format-language
【解决方案1】:
来自Auto Layout Guide: Visual Format Language的文档
符号更喜欢良好的可视化而不是完整性
可表达性。大多数对真实用户有用的约束
接口可以使用可视化格式语法来表达,但是有
一些不能。一个无法表达的有用约束是
固定纵横比(例如,imageView.width = 2 *
图像视图.高度)。要创建这样的约束,您必须使用
constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:.
“宽度等于高度”是一个比率(对 1)。所以这是不可能的。
【解决方案2】:
我不认为你可以,因为这是一个非常不常见的设置。像这样的深奥用例是最好在 NSLayoutConstraint 上使用显式初始化程序的地方。
【解决方案3】:
如前所述,文档指出您不能使用 VFL 设置某些(常见)约束。这是一个简单的示例,只需添加 一个 附加行即可获得所需的内容。
您可以在 Playground 中运行它:
import UIKit
import PlaygroundSupport
class TestVC: UIViewController {
let squareView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .green
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
// add the subview
view.addSubview(squareView)
//Views to add constraints to
let views = Dictionary(dictionaryLiteral: ("sqV", squareView))
// 40 points from left, width of 100
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-40-[sqV(==100)]", options: [], metrics: nil, views: views)
view.addConstraints(horizontalConstraints)
// 40 points from top, no height setting
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-40-[sqV]", options: [], metrics: nil, views: views)
view.addConstraints(verticalConstraints)
// set height equal to width (1:1 ratio)
squareView.heightAnchor.constraint(equalTo: squareView.widthAnchor, multiplier: 1.0).isActive = true
}
}
let vc = TestVC()
PlaygroundPage.current.liveView = vc