从左到右平滑地重复动画

Hap*_*eki 3 uiview uiviewanimation ios swift

我正在尝试从左到右为 3 个方块设置动画。当它们从右侧消失时,方块应该从左侧重新出现。这个想法是正方形代表云,所以这个想法很清楚。

这是我目前得到的:

class ViewController: UIViewController {

    // contains the squares
    @IBOutlet weak var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        startAnimating()
    }

    func startAnimating() {
        UIView.animateKeyframes(withDuration: 10, delay: 0, options: .repeat, animations: {
            self.containerView.center.x += self.view.bounds.width

        }, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是结果:

云

方块从左向右移动。这很好。问题是一旦动画完成,方块就会从它们开始的地方重新出现。这不是一个平滑的连续运动,即云从左向右移动,然后又从左慢慢重新出现。你如何做到这一点?应该有第二个 containerView 吗?或者删除 containerView 并为单个云设置动画?

答案米兰诺萨?解决了这个问题。一个注意事项:

我将 containerView2 放置在具有完全相同约束的 containerView1 之上(它们彼此重叠)。只要确保 IB 不包含 containerView2 作为 containerView1 的子视图。

Mil*_*sáľ 5

我想你知道的最简单的方法是使用两个完全相同的容器。您可以使用完全相同的代码,并将containerView2上面的代码放在containerView一起以确保相互覆盖。

然后简单地使用:

class ViewController: UIViewController {

    // contains the squares
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var containerView2: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // this will transform the containerView2 to the left to appear as if it was exactly to the left of the containerView
        containerView2.transform = CGAffineTransform.identity.translatedBy(x: -self.view.bounds.width, y: 0)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        startAnimating()
    }

    func startAnimating() {
        UIView.animateKeyframes(withDuration: 10, delay: 0, options: .repeat, animations: {
            self.containerView.center.x += self.view.bounds.width
            self.containerView2.center.x += self.view.bounds.width

        }, completion: nil)
    }

}
Run Code Online (Sandbox Code Playgroud)

containerView2会代表未来从左边后面的云。