【问题标题】:Should I enclose "addArrangedSubview" to the animation block or not?我是否应该将“addArrangedSubview”附在动画块中?
【发布时间】:2015-09-10 23:54:55
【问题描述】:

我不是在学习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.horizontalStackView.addArrangedSubview(starImgVw) 移动到动画块的内部。

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

所以我的问题如下:

  • 哪种方法更好?

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

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

【问题讨论】:

    标签: ios animation uiview uistackview


    【解决方案1】:

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

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

    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
    }
    

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

    【讨论】:

    • 很抱歉回复晚了,但非常感谢您的出色澄清。
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 2016-10-28
    • 2011-06-08
    相关资源
    最近更新 更多