swift - addSubview swift 破坏动画

标签 swift animation asynchronous subview

调用动画的方法

    for button in self.exploreButtonsArray {
        button.exploreButtonExitAnimation()
    }

    setupDrinkExploreButtons()

动画代码:

func exploreButtonExitAnimation() {
    UIView.animateWithDuration(random, delay: 0.0, options: [], animations: {
        self.center.x -= 400
        }, completion: {(value: Bool) in
            self.removeFromSuperview()
    })

}

setupDrinkExploreButtons() 方法调用 .addSubview(exploreButton) 并将一些按钮添加到容器中。我的动画是不是因为这些 Action 是异步执行的而搞砸了?

This is the very first view before any animation

How the view looks without calling setupDrinkExploreButtons()

What it looks like when calling setupDrinkExploreButtons()

第一张图片:这是任何动画之前的第一个 View

第二张图片:未调用 setupDrinkExploreButtons() 时 View 的外观。所有按钮都优雅地向左移动。

第三张图片:调用 setupDrinkExploreButtons() 时的样子

在第 3 个图像中,您可以看到按钮如何没有消失,而是它们似乎“动画化”以适应 View 。他们没有像他们应该的那样向左移动 400 个单位,而是突然出现在右侧 400 个单位,然后向左移动以适应他们原来的位置???

最佳答案

我最好的猜测是您在 self.exploreButtonsArray 中使用了对旧 View 和新 View 的相同引用,或者在创建新 View 时清空了数组。如果你想发布你的代码,我可以看看。

不过,我有几点建议:

首先,这是一种不太可靠的制作动画的方法。您将创建十几个动画 block ,根据时间的不同,它们可能会在略有不同的时间开始和结束。这可能会引起注意,也可能不会引起注意,但这是一个坏习惯,而且效率较低。为避免此问题,您可以执行以下操作:

UIView.animate(withDuration: random, delay: 0.0, options: [], animations: {
    for button in self.exploreButtonsArray {
        // BTW this is also unreliable, I would strongly suggest using definite values when animating
        button.center.x -= 400
    }
}, completion: { (finished) in
    for button in self.exploreButtonsArray {
        button.removeFromSuperview()
    }
})

其次,如果您像这样将 View 组合在一起,最好将它们全部放在一个 View 中,然后为该 View 设置动画。这对于性能和编码时更简单。

第三,您似乎正在尝试进行一些非常简单的分页。如果您只是想玩得开心并且想自己实现它,那就去做吧!如果没有,您可能想使用 UIPageViewControllerUICollectionViewController .我保证这将意味着更少的头痛:)

关于swift - addSubview swift 破坏动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086570/

相关文章:

ios - AVCaptureVideoPreviewLayer 未显示预览中心

javascript - 动画背景位置不同的行为

javascript - 如何等到循环内的异步进程完成后再退出循环?

java - 将第一个 CompletableFuture 的结果传递给链上的其他 CompletableFuture

c# - 如何中止套接字的 BeginReceive()?

swift - UIActivityViewController - 不能同时 AirDrop 多个对象类型

swift - 将文件移动到我自己的应用程序中存在同名文件的目录时,是否可以使用 Finder 提供的警报?

ios - 动态更改所有 Uitableviewcells 高度以快速填充 uitableview

javascript - 启动/停止 webkit 动画 onclick 而不是 :hover

css - 背景图片 CSS3 无限循环动画