设置水平方向的布局, view1距离superView左边20个单位, view1的宽度是50, view1的右边是view2, view1和view2的距离是11个单位长度, view2距离superView右边20个单位长度.
列子2:H:[wideView(>=60@700)]
wideView宽度大于等于60point,该约束条件优先级为700(优先级最大值为1000,优先级越高的约束条件越先被满足)
`例子3:V:|-20-[redBox(50)]-20-[yellowBox(==redBox)]``
垂直方向上, redBox距离上面20个单位, redBox的高度是50个单位, redBox右边20个单位之外是yellowBox, yellowBox的高度和redBox的高度相等.
4.2 代码示例NSLayoutConstraint.constraints在API中的定义如下所示,
/* Create an array of constraints using an ASCII art-like visual format string. */ open class func constraints(withVisualFormat format: String, options opts: NSLayoutFormatOptions = [], metrics: [String : Any]?, views: [String : Any]) -> [NSLayoutConstraint] /* This macro is a helper for making view dictionaries for +constraintsWithVisualFormat:options:metrics:views:. NSDictionaryOfVariableBindings(v1, v2, v3) is equivalent to [NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", v2, @"v2", v3, @"v3", nil]; */ format:VFL语句 opts:约束类型 metrics:VFL语句中用到的具体数值 views:VFL语句中用到的控件 创建一个字典(内部包含VFL语句中用到的控件)的快捷宏定义 NSDictionaryOfVariableBindings(...)如下是设置redView和greenView的一个代码示例, VFL支持同时设置多个view的约束, 也支持设置相对约束.
let redView = UIView() redView.backgroundColor = UIColor.red redView.translatesAutoresizingMaskIntoConstraints = false let blueView = UIView() blueView.backgroundColor = UIColor.blue blueView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(redView) view.addSubview(blueView) //设置redView的constraints view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[view(200)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": redView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[view(200)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": redView])) //设置blueView的约束, 此时blueView的约束是相对于redView来设置 //实际上, 可以同时设置redView和blueView的约束, 这里拆开是为了测试VFL支持相对约束 let hMetrics = ["middleSpace": 10, "rightSpace": 20] let hViews = ["redView": redView, "blueView": blueView] let hVFL = "H:[redView]-middleSpace-[blueView]-rightSpace-|" view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: hVFL, options: NSLayoutFormatOptions() metrics: hMetrics, views: hViews)) let vMetrics = ["topSpace": 10, "height": 80] let vViews = hViews let vVFL = "V:[redView]-topSpace-[blueView(height)]" view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: vVFL, options: NSLayoutFormatOptions() metrics: vMetrics, views: vViews))转载请注明出处!