从左到右平滑地重复动画

Repeat animation from left to right smoothly

我正在尝试制作从左到右的 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)
    }
}

这是结果:

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

Milan Nosáľ 的回答解决了这个问题。不过请注意:

I placed containerView2 above containerView1 with the exact same constraints (they overlap each other). Just make sure IB doesn't include containerView2 as a subview of containerView1.

您可以尝试在开始动画之前放置 containerView.center.x -= 200。这样它首先从左侧出现。

我想您知道的最简单的方法是使用两个完全相同的容器。您可以使用完全相同的代码,并将 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)
    }

}

containerView2代表云从左边回来。