mac 代码给控件添加约束

mac上用代码给控件添加约束和iOS上是一样的。

   let blueView = NSView.init()
    blueView.wantsLayer = true
    blueView.layer?.backgroundColor = NSColor.blue.cgColor
    blueView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(blueView)
    
    let topConstraint = NSLayoutConstraint.init(item: blueView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 40)
    topConstraint.isActive = true
    
    let leftConstraint = NSLayoutConstraint.init(item: blueView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1.0, constant: 20)
    leftConstraint.isActive = true
    
    let widthConstraint = NSLayoutConstraint.init(item: blueView, attribute: .width, relatedBy:.equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 200)
    widthConstraint.isActive = true
    
    let heightConstraint = NSLayoutConstraint.init(item: blueView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100)
    heightConstraint.isActive = true

也可以这么写

    let redView = NSView.init()
    redView.wantsLayer = true
    redView.layer?.backgroundColor = NSColor.red.cgColor
    
    redView.translatesAutoresizingMaskIntoConstraints = false
    let contraints = [
        redView.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 20),
        redView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
        redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
        redView.bottomAnchor.constraint(equalTo: view.bottomAnchor,constant: -20)
    ]
    NSLayoutConstraint.activate(contraints)

你可能感兴趣的:(mac 代码给控件添加约束)