我应该将“addArrangedSubview”附在动画块中吗?

Bla*_*ard 4 animation uiview ios uistackview

我没有在网上学习使用UIStackView和阅读好的教程。在教程中,作者编写了如下代码来制作动画:

@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()
    })
}
Run Code Online (Sandbox Code Playgroud)

但是,当我克隆存储库并稍微更改代码时,我仍然正确地看到了相同的动画。

@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()
    })
}
Run Code Online (Sandbox Code Playgroud)

我移动self.horizontalStackView.addArrangedSubview(starImgVw)到动画块的内部。

我也在removeStar功能上尝试了同样的事情;这次移动了self.horizontalStackView.removeArrangedSubview(aStar)aStar.removeFromSuperview(),但我也确认动画正常工作。

所以我的问题如下:

  • 哪种方法更好?

  • 为什么这两个代码以相同的方式工作?

  • 当我删除时layoutIfNeeded(),动画不起作用。这是因为如果我不强制立即更新视图,那么下一个视图更新周期发生在动画块之后,因此动画不再有效,对吗?

Rob*_*ack 9

在动画块中,您只想包含想要看到动画的更改。您不应该同时包含多个更改,因为这样功能会变得有点不可预测。您将不确定哪个更改会优先于其他更改。

所以要回答你的问题,你的第一个例子

UIView.animateWithDuration(0.25, animations: {
    self.horizontalStackView.layoutIfNeeded()
})
Run Code Online (Sandbox Code Playgroud)

是编写这段代码的更好方法。

只有 UIView 的特定属性是可动画的。来自苹果的文档:

The following properties of the UIView class are animatable:
@property frame
@property bounds
@property center
@property transform
@property alpha
@property backgroundColor
@property contentStretch
Run Code Online (Sandbox Code Playgroud)

本质上,通过调用layoutIfNeeded,您允许animateWithDuration在处理器布局之前为星形视图添加约束动画。这就是为什么你看到它向右移动。

删除layoutIfNeeded()只会让您添加子视图功能。添加子视图不能使用 animateWithDuration 函数进行动画处理。这就是它不起作用的原因。您可以通过在首次创建时将 alpha 设置为 0.0,然后animateWithDuration将 alpha 设置为 1.0来使其看起来具有动画效果。

starImgVw.alpha = 0.0
horizontalStackView.addArrangedSubview(starImgVw)

UIView.animateWithDuration(0.25) { () -> Void in
    starImgVw.alpha = 1.0
}
Run Code Online (Sandbox Code Playgroud)

我希望能完全回答你的问题。