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

5

我正在学习如何使用 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()
    })
}

然而,当我克隆仓库并稍微修改代码后,我仍然可以正确地看到相同的动画。
@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()
    })
}

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

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

所以我的问题如下:

  • 哪种方式更好?

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

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

1个回答

10
在动画块中,您只需包含您想要进行动画处理的更改。不应该同时包含多个更改,因为这样功能会变得有点不可预测。您不确定哪个更改将优先于其他更改。
因此,回答您的问题,您提供的第一个示例应该是:
UIView.animateWithDuration(0.25, animations: {
    self.horizontalStackView.layoutIfNeeded()
})

这是编写此代码片段更好的方式。

只有 UIView 的特定属性是可动画的。根据 Apple 的文档:

The following properties of the UIView class are animatable:
@property frame
@property bounds
@property center
@property transform
@property alpha
@property backgroundColor
@property contentStretch

使用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
}

我希望这充分回答了你的问题。


1
抱歉回复有点晚,但非常感谢您提供的出色澄清。 - Blaszard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接