Home > Software design >  How to update constraints programmatically if I would like to change every time
How to update constraints programmatically if I would like to change every time

Time:05-09

I have an imageView that is supposed to go up or down according to a value changing every time.

I am keeping a reference to the bottom constraint of imageView and changing this constant according to constant value.

These associated codes are in my ViewController which has my imageView as a subview.

private var imageConstraint = 50.0

//viewDidLoad

       imageView.snp.makeConstraints {
           $0.width.height.equalTo(48)
           $0.centerX.equalToSuperview()
           $0.bottom.equalTo(-imageConstraint)
       }

I try to put this into x method imageView stay at the same place.

DispatchQueue.main.async {
    unownedSelf.imageView.layoutIfNeeded()
}

How can I fix and change constraints the same as the changing value?

PS: I could not put the entire code because it is so long so I share related parts. Thanks for your understanding.

CodePudding user response:

Since you are using SnapKit, you need to use its .updateConstraints syntax.

This example will toggle .imageConstraint between 50.0 and -50.0 on any touch, and animate the image view:

class SnapVC: UIViewController {
    
    let imageView = UIImageView()
    
    private var imageConstraint = 50.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let img = UIImage(named: "myImage") {
            imageView.image = img
        }
        
        view.addSubview(imageView)
        
        imageView.snp.makeConstraints {
            $0.width.height.equalTo(48)
            $0.centerX.equalToSuperview()
            $0.bottom.equalTo(-imageConstraint)
        }
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        imageConstraint *= -1
        imageView.snp.updateConstraints {
            $0.bottom.equalTo(-imageConstraint)
        }
        UIView.animate(withDuration: 0.5, animations: {
            self.view.layoutIfNeeded()
        })
    }

}
  • Related