OGeek|极客世界-中国程序员成长平台

标题: ios - 我是否应该将 "addArrangedSubview"附在动画 block 中? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:41
标题: ios - 我是否应该将 "addArrangedSubview"附在动画 block 中?

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

@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.horizo​​ntalStackView.addArrangedSubview(starImgVw) 移到了动画 block 的内部。

我也在 removeStar 函数上尝试过同样的事情;这次移动了 self.horizo​​ntalStackView.removeArrangedSubview(aStar)aStar.removeFromSuperview(),但我也确认动画可以正常工作。

所以我的问题如下:



Best Answer-推荐答案


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

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

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 在处理器布局之前将约束添加到星形 View 。这就是你看到它向右移动的原因。

删除 layoutIfNeeded() 只会让您添加 subview 功能。 使用 animateWithDuration 函数无法为 subview 添加动画。这就是为什么它不起作用。您可以在首次创建时将 alpha 设置为 0.0,然后在 animateWithDuration 中将 alpha 设置为 1.0,从而使其看起来具有动画效果。

starImgVw.alpha = 0.0
horizontalStackView.addArrangedSubview(starImgVw)

UIView.animateWithDuration(0.25) { () -> Void in
    starImgVw.alpha = 1.0
}

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

关于ios - 我是否应该将 "addArrangedSubview"附在动画 block 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513377/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4