参考:SnapKit - 修改约束

https://blog.csdn.net/longshihua/article/details/80289061

 import SnapKit


class ViewController: UIViewController {
    
    private var isUpdateSnapkitV  = false
    
    private lazy var snapkitV : UIView = {
        let snapkitV = UIView()
        snapkitV.backgroundColor = UIColor.red
        return snapkitV
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(snapkitV)
        snapkitV.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(reloadView)))
        snapkitV.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 100, height: 100))
            make.centerX.centerY.equalTo(view)
        }
    }
    
    
    override func updateViewConstraints() {
        
        //移除原有的重新添加
        snapkitV.snp.remakeConstraints { (make) in
            if isUpdateSnapkitV{
                make.size.equalTo(CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width))
            }else{
                make.size.equalTo(CGSize(width: 100, height: 100))
            }
        }
        
        //更新原有的不会添加
        snapkitV.snp.updateConstraints { (make) in
            if isUpdateSnapkitV{
                make.size.equalTo(CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width))
            }else{
                make.size.equalTo(CGSize(width: 100, height: 100))
            }
        }
        
        //最后一步在调用
        super.updateViewConstraints()
    }
}

extension ViewController{

///第一种更新动画方法 推荐 https://www.cnblogs.com/qingzZ/p/14005859.html


///第二种动画方法 不推荐 @objc private func reloadView(){ isUpdateSnapkitV.toggle() self.view.setNeedsUpdateConstraints() //标记为需要更新约束 self.view.updateConstraintsIfNeeded()//立即调用updateViewConstraints更新约束, 此方法只是更新了约束, 并没有刷新布局 UIView.animate(withDuration: 1.0) { self.view.layoutIfNeeded()//动画 刷新布局 } } }


设置内边距inset

        bgView.snp.remakeConstraints { make in

            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 16, bottom: 16, right: 16)).priority(.high);

        }

 

  

posted on 2019-07-04 14:31  懂事长qingzZ  阅读(977)  评论(0编辑  收藏  举报