Swift-- NSLayoutConstraint

曹景铄
2023-12-01

NSLayoutConstraint
iOS自带的布局类, 一般我们在XIb中给一个控件进行布局,上左下右各是多少可以随意设置,而不用Xib用代码怎么写,写法如下:

self.view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false  //关闭AutoResizing 这种布局方式早就不用了,需要关闭

 [ 
    btn.rightAnchor.constraint(equalTo: self.view.rightAnchor)
    btn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
    btn.widthAnchor.constraint(equalTo: btn.heightAnchor)
    btn.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.25)          
              
 ].forEach{$0.isActive = true}

对比使用第三方SnapKit用法

self.view.addSubview(btn)
btn.snp.makeConstraints { (make) in
            make.right.equalTo(self.view.snp.right)
            make.width.equalTo(btn.snp.height)
            make.centerY.equalTo(self.view.snp.centerY)
            make.width.equalTo(self.view.snp.height).multipliedBy(0.25)
        }

可以看到两种写法没有优劣,甚至感觉语法颇相似,习惯哪种而已,今日之前忘记了NSLayoutConstraint苹果提供的代码写法,聊以记录。

 类似资料: