When we use the Frame layout control, if the frame of the control changes, we want the change to be an animated transition rather than a blunt direct change. We can use the UIView the animate (withDuration: animations: completion:) function to implement, the code below:

Uiview.animate (withDuration: 0.5) {// Alter frame self.exampleView.frame = CGRect(x: 10, y: 10, width: 100, height: 100)}Copy the code

So when we use AutoLayout layout, we want to achieve the above effect how to write?

This can be done through the following two steps:

  • Change the target control constraint
  • callanimate(withDuration:animations:completion:)function
    • Of the target control’s parent viewlayoutIfNeeded()function

Concrete example

Declare global variables

private let exampleView = UIView(frame: .zero)
private var topConstraint = NSLayoutConstraint()
Copy the code

Use the AutoLayout layout control

extension ViewController {
    private func setupSubviews() {
        
        exampleView.backgroundColor = .green
        view.addSubview(exampleView)
        
        exampleView.translatesAutoresizingMaskIntoConstraints = falsetopConstraint = exampleView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100) topConstraint.constant = 100 NSLayoutConstraint.activate([ topConstraint, exampleView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 100), exampleView.widthAnchor.constraint(equalToConstant: 100), exampleView.heightAnchor.constraint(equalToConstant: 100)])let button = UIButton(type: .custom)
        button.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
        view.addSubview(button)
    }
}
Copy the code

Animation change constraint

extension ViewController { @objc func buttonAction(_ sender: UIButton) {// Modify topconstraint.constant = 200 // Call the parent view's layoutIfNeeded() uiView.animate (withDuration: 0.5) {self.view.layoutifneeded ()}}}Copy the code

Renderings – Animation changes constraints

Matters needing attention

  • In the target control to callParent viewthelayoutIfNeeded()function
  • Notice that this is calledlayoutIfNeeded()Delta function, nosetNeedsLayout()
  • reference