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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容