Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate the item height in vertical stack view correctly?

Tags:

ios

swift

I have the a red color stack view.

It contains a label and a purple custom view.

It looks as following

enter image description here

What I would like to achieve is

  1. Label's top left (x, y) will always remain the same during animation.
  2. Purple custom view's top left (x, y) will always remain the same during animation.
  3. During animation, the red stack view will animate gracefully, based on the animation of purple custom view.

I use the following code

class ViewController: UIViewController {

    @IBOutlet weak var purpleView: UIView!
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var purpleViewHeightConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    var value: CGFloat = 200.0
    @IBAction func buttonClicked(_ sender: Any) {
        if value == 500 {
            value = 200.0
        } else {
            value = 500.0
        }
        
        UIView.animate(withDuration: 2) {
            self.purpleViewHeightConstraint.constant = self.value
            self.purpleView.setNeedsLayout()
            self.purpleView.layoutIfNeeded()
        }
    }
}

This is what I have achieved.

enter image description here

We can observe

  1. The height of red stack view will change abruptly, without following the animation of its child purple view.

Without removing UIStackView, how can I achieve?

  1. Label's top left (x, y) will always remain the same during animation.
  2. Purple custom view's top left (x, y) will always remain the same during animation.
  3. During animation, the red stack view will animate gracefully, based on the animation of purple custom view.

I post the demo project - https://github.com/yccheok/animate-stack-view-item

Thanks.

like image 304
Cheok Yan Cheng Avatar asked Oct 27 '25 01:10

Cheok Yan Cheng


1 Answers

Set your button action like this

@IBAction func buttonClicked(_ sender: Any) {
        if value == 500 {
            value = 200.0
        } else {
            value = 500.0
        }
        self.purpleViewHeightConstraint.constant = self.value
        UIView.animate(withDuration: 2) {
            self.view.layoutIfNeeded()
        }
    }

enter image description here

like image 51
Raja Kishan Avatar answered Oct 29 '25 16:10

Raja Kishan