I'm not learning the use of UIStackView
and read a good tutorial on the web. In the tutorial, the author writes the following code to make an animation:
@IBAction func addStar(sender: AnyObject) {
let starImgVw:UIImageView = UIImageView(image: UIImage(named: "star"))
starImgVw.contentMode = .ScaleAspectFit
self.horizontalStackView.addArrangedSubview(starImgVw)
UIView.animateWithDuration(0.25, animations: {
self.horizontalStackView.layoutIfNeeded()
})
}
However, when I cloned the repository and changed the code slightly, I still saw the same animation properly.
@IBAction func addStar(sender: AnyObject) {
let starImgVw:UIImageView = UIImageView(image: UIImage(named: "star"))
starImgVw.contentMode = .ScaleAspectFit
UIView.animateWithDuration(0.25, animations: {
self.horizontalStackView.addArrangedSubview(starImgVw)
self.horizontalStackView.layoutIfNeeded()
})
}
I moved self.horizontalStackView.addArrangedSubview(starImgVw)
to the inner part of the animation block.
I also tried the same thing on removeStar
function; this time moved both self.horizontalStackView.removeArrangedSubview(aStar)
and aStar.removeFromSuperview()
, but I also confirmed the animation work properly.
So my question is the following:
Which is the better way?
Why do these two code work in the same way?
When I removed
layoutIfNeeded()
, then the animation didn't work. This is because if I don't force the views to be updated immediately, then the next view update cycle occurs after the animation block and thus the animation is no longer valid, right?