參考: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{ @objc private func reloadView(){ isUpdateSnapkitV.toggle() self.view.setNeedsUpdateConstraints() //標記為需要更新約束 self.view.updateConstraintsIfNeeded()//立即調用updateViewConstraints更新約束, 此方法只是更新了約束, 並沒有刷新布局 UIView.animate(withDuration: 1.0) { self.view.layoutIfNeeded()//動畫 刷新布局 } } }