iOS NSLayoutConstraint 代码实现系统自动布

2021-03-10  本文已影响0人  Jason_li012

1: 系统布局两种方式

     /// first
     /// 以数组方式激活每一个约束
     middleView.translatesAutoresizingMaskIntoConstraints = false
     NSLayoutConstraint.activate([
         middleView.leftAnchor.constraint(equalTo: self.leftAnchor),
         middleView.rightAnchor.constraint(equalTo: self.rightAnchor),
         middleView.topAnchor.constraint(equalTo: self.topAnchor),
         middleView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
     ])
        
     /// second
     /// 单独设置激活每一个约束
     /// 缺点: 每一个约束都要单独激活 isActive 为ture
     /// 优点: 方便后面可以更新约束(两种方式:1、identifier 2、constant)
     smallView.translatesAutoresizingMaskIntoConstraints = false
     smallView.leftAnchor.constraint(equalTo: middleView.leftAnchor, constant: 20).isActive = true
     smallView.rightAnchor.constraint(equalTo: middleView.rightAnchor, constant: -20).isActive = true
     smallView.bottomAnchor.constraint(equalTo: middleView.bottomAnchor).isActive = true
     smallView.heightAnchor.constraint(equalToConstant: 40).isActive = true

translatesAutoresizingMaskIntoConstraints 默认为true,则是系统会自动创建一组约束,因此要想创建自动布局,动态调整位置和大小。必须置为false

2: 修改约束

1: 设置某个约束唯一标识符 identifier

场景: 根据上面约束样式代码,现在我要把棕色smallView 往上移动20px,
先设置底部bottomAnchor 约束identifier

     /// 设置 identifier
     NSLayoutConstraint.activate([
         smallView.leftAnchor.constraint(equalTo: middleView.leftAnchor, constant: 20),
         smallView.rightAnchor.constraint(equalTo: middleView.rightAnchor, constant: -20),
         smallView.heightAnchor.constraint(equalToConstant: 40)
     ])
        
     let bottomAnchor  = smallView.bottomAnchor.constraint(equalTo: middleView.bottomAnchor, constant: 0)
     bottomAnchor.identifier = "samllView"
     bottomAnchor.isActive = true

然后点击上移20px按钮,实现方法:

     /// 遍历 samllView 的父视图 middleView 中的 constraints 子类
     /// identifier 为 ”samllView“的约束,然后停用此约束
     /// 然后再添加 bottomAnchor 约束
     let constraint = middleView.constraints.filter { $0.identifier == "samllView" }
     NSLayoutConstraint.deactivate(constraint)
     let bottomAnchor = smallView.bottomAnchor.constraint(equalTo: middleView.bottomAnchor, constant: -20)
     bottomAnchor.identifier = "samllView"
     bottomAnchor.isActive = true
     middleView.addConstraint(bottomAnchor)

2 设置全局变量 bottomAnchor 然后修改 constant

    /// 声明全局变量
   var bottomAnchors: NSLayoutConstraint?

    /// 设置 constant
     NSLayoutConstraint.activate([
         smallView.leftAnchor.constraint(equalTo: middleView.leftAnchor, constant: 20),
         smallView.rightAnchor.constraint(equalTo: middleView.rightAnchor, constant: -20),
         smallView.heightAnchor.constraint(equalToConstant: 40)
     ])
 
     bottomAnchors = smallView.bottomAnchor.constraint(equalTo: middleView.bottomAnchor, constant: 0)
     bottomAnchors?.isActive = true

实现方法:

 @objc func buttonAction() {
      bottomAnchors?.constant = -20
   }

修改前:

image.png

修改后:

image.png
上一篇 下一篇

猜你喜欢

热点阅读