如何使用视觉格式语言在Swift中设置约束?

时间:2019-01-04 23:10:53

标签: ios swift visual-format-language

我有一个带有导航栏的View Controller,我试图在导航栏正下方实现一个菜单栏,为此我有一个单独的类文件(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")
}

//功能addConstraintWithFormat(- format:, views:)的UIView扩展

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))

}

1 个答案:

答案 0 :(得分:2)

Visual Format Language允许您使用视觉语法字符串应用程序约束。根据{{​​3}},想法是文本在视觉上与布局匹配。

为了更好的理解,让我们分解一下语法部分:

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为假,我们将在该视图上应用约束:

imageView.translatesAutoresizingMaskIntoConstraints = false

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

let viewDictionary = NSDictionaryOfVariableBindings(imageView)

然后按照上述规则使用Visual Format String进行水平和垂直约束:

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:如果要使视图的宽度/高度动态变化,则需要创建一个矩阵字典,将其传递到metrics:中而不是将其设置为nil,然后使用适当的键名作为值。例如:

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