参考: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( 100, height: 100)) make.centerX.centerY.equalTo(view) } } override func updateViewConstraints() { //移除原有的重新添加 snapkitV.snp.remakeConstraints { (make) in if isUpdateSnapkitV{ make.size.equalTo(CGSize( UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width)) }else{ make.size.equalTo(CGSize( 100, height: 100)) } } //更新原有的不会添加 snapkitV.snp.updateConstraints { (make) in if isUpdateSnapkitV{ make.size.equalTo(CGSize( UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width)) }else{ make.size.equalTo(CGSize( 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()//动画 刷新布局 } } }