NSLayoutConstraint

直接上码!

 let a = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 200, height: 200)))
        self.view.addSubview(a)
        a.backgroundColor = UIColor.brown
        a.translatesAutoresizingMaskIntoConstraints = false //把自动调整关掉,不然会出错
        
        let width = NSLayoutConstraint(item: a, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0)
        a.superview?.addConstraint(width)
        
        let height = NSLayoutConstraint(item: a, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 300)
        a.addConstraint(height)
        
        let centerX = NSLayoutConstraint(item: a, attribute: .centerX, relatedBy: .equal, toItem: self.view , attribute: .centerX, multiplier: 1.0, constant: 0.0)
        a.superview?.addConstraint(centerX)  //是superview,不然会报not in view tree错误
        
        let centerY =
        NSLayoutConstraint(item: a, attribute: .centerY, relatedBy: .equal, toItem: self.view , attribute: .centerY, multiplier: 1.0, constant: 0.0)
        a.superview?.addConstraint(centerY)