swift4--纯代码添加约束

NLayouConstraint类中提供了constraints()方法,来将VFL字符串翻译成约束对象。这个方法中的widthVisualForma参数为VFL字符串,views参数要设置为VFL字符串中使用到的视图控件的名称与对应的视图控件对象的映射。在VFL语言中,H代表水平方向的约束,V代表竖直方向的约束,|符号表示父视图的边沿,-20-表示相距20个单位的距离,[ ] 内是要摆放的视图控件名称,( ) 内为约束值。因此,下面的两句VFL代码可以解释为,约束视图的高度为200,约束其距离父视图左、上、右边距为60个单位。

//
//  ViewController.swift
//  纯代码添加约束
//


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let redView = UIView()
//                禁止将AutoresizingMask转化为Constraints
        redView.translatesAutoresizingMaskIntoConstraints = false
        redView.backgroundColor = UIColor.red
        self.view.addSubview(redView)
        //        创建约束
        let constraintArrayH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-60-[redView]-60-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["redView":redView])
        let constraintArrayV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[redView(200)]", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["redView":redView])
                //添加多个约束
        self.view.addConstraints(constraintArrayH)
        self.view.addConstraints(constraintArrayV)
        
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_41735943/article/details/83041106