I have the a red color stack view.
It contains a label and a purple custom view.
It looks as following
What I would like to achieve is
- Label's top left (x, y) will always remain the same during animation.
- Purple custom view's top left (x, y) will always remain the same during animation.
- 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.
We can observe
- 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?
- Label's top left (x, y) will always remain the same during animation.
- Purple custom view's top left (x, y) will always remain the same during animation.
- 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.


