【问题标题】:Repeat animation from left to right smoothly从左到右平滑地重复动画
【发布时间】:2018-01-16 13:57:05
【问题描述】:

我正在尝试从左到右为 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 并对单个云进行动画处理?

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

我将 containerView2 放在 containerView1 上方,完全相同 约束(它们相互重叠)。只要确保 IB 没有 包含 containerView2 作为 containerView1 的子视图。

【问题讨论】:

  • 我的回答都清楚了吗?
  • @MilanNosáľ 谢谢,一切都说得通,虽然我不知道如何将 containerView2 放在 containerView1 的左侧,因为 containerView 使用了 viewController 的整个宽度
  • 现在检查一下......对于奇怪的“hackarounds”感到抱歉,但我通常不使用故事板,因此以编程方式布置内容对我来说似乎很容易

标签: ios swift uiview uiviewanimation


【解决方案1】:

我想你知道的最简单的方法是使用两个完全相同的容器。您可以使用完全相同的代码,并将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 将代表从左侧返回的云。

【讨论】:

  • 这有效,现在我必须微调动画,但您的回答解决了问题,谢谢!
【解决方案2】:

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

【讨论】:

  • 这意味着云在 center.x > 0 之前是不可见的
猜你喜欢
  • 1970-01-01
  • 2011-07-06
  • 2021-07-05
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
相关资源
最近更新 更多