Swift如何使用Visual Format Language设置约束条件?

How to use Visual Format Language to set constraints in Swift?

我有一个带有导航栏的视图控制器,我正在尝试在导航栏正下方实现一个菜单栏,为此我有一个单独的 class 文件 (UIView)。添加菜单栏后,我想在菜单栏视图的垂直中心添加一个 UIImageView 而不是超级视图,并且高度与菜单栏视图相同。我正在使用视觉格式语言。我不太确定如何提及视图的名称以及如何限制图像的高度并将其放置在命名视图的中心。有人可以帮助我吗?

下面是代码片段...

//MenuBar.swift

class MenuBar: UIView {


override init(frame: CGRect) {

    super.init(frame: frame)
    print("created") 

    let imageLogo = UIImage(named: "Logo")
    let imageView = UIImageView(image: imageLogo)
    self.addSubview(imageView)
    self.addConstraintWithFormat("H:|[v0]|", views: imageView)
    self.addConstraintWithFormat("V:|[v0(100)]|", views: imageView)
    backgroundColor = UIColor.red
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

//函数的 UIView 扩展 addConstraintWithFormat(- format:, views:)

extension UIView{
func addConstraintWithFormat(_ format : String, views : UIView...) {

    var viewsDictionary = [String : UIView]()

    for(index, view) in views.enumerated(){
        let key = "v\(index)"
        view.translatesAutoresizingMaskIntoConstraints = false
        viewsDictionary[key] = view
    }
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDictionary))

}

视觉格式语言允许您使用视觉语法字符串应用编程约束。根据 Apples Documentation,想法是文本在视觉上与布局相匹配。

让我们分解语法部分以便更好地理解:

H: (Horizontal) //horizontal direction
V: (Vertical) //vertical direction
| (pipe) //superview
- (dash) //standard spacing (generally 8 points)
[] (brackets) //name of the object (uilabel, unbutton, uiview, etc.)
() (parentheses) //size of the object
== equal widths //can be omitted
-16- non standard spacing (16 points)
<= less than or equal to
>= greater than or equal to
@250 priority of the constraint //can have any value between 0 and 1000

现在,为了使用视觉格式语言将约束应用于视图,我们需要为视图设置 translatesAutoresizingMaskIntoConstraints false,我们将在其上应用约束:

imageView.translatesAutoresizingMaskIntoConstraints = false

然后我们需要为所有视图准备一个字典,这些视图将在 VFL 中使用,如:

let viewDictionary = NSDictionaryOfVariableBindings(imageView)

然后按照上述规则使用可视格式字符串进行水平和垂直约束:

let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[imageView]-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[imageView(100)]-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDictionary)

现在,将这些常量添加到您的超级视图中,例如:

view.addConstraints(horizontalConstraints)
view.addConstarints(verticalConstraints)

PS:如果你想让view的width/height动态,​​你需要创建一个矩阵字典,传入metrics:而不是设置它nil和然后使用适当的键名作为值。例如:

let metricDict = ["viewHeight":300]
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[imageView(viewHeight)]-|", options: NSLayoutConstraint.FormatOptions(), metrics: metricDict, views: viewsDictionary)