在隐藏Label之前,UIView动画没有完成

时间:2017-11-15 22:50:09

标签: ios swift uiview

我的标签在动画运行之前就消失了。

按下按钮后动画应该会运行并滑出标签和按钮。但是当我按下按钮时,它们都会被隐藏,然后动画才能将它们滑出来。

2017-11-15 23:26:17.321465 [2442:245232] Animation started
2017-11-15 23:26:20.325137 [2442:245232] Animation stopped

这是NSLog。据说它正在运行完整的动画......

undefined

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您的代码完美无缺:

enter image description here

因此,告诉我们的事情是造成问题的原因。

编辑:确实如此,您没有告诉我们的代码会导致问题。你告诉我们这个:

UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
})


但是您没有告诉我们下一行行,这是:

labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)

这些行取消了动画!

似乎你还没有理解动画是什么。首先制作动画,然后在动画之后完成 动画的任何内容,然后输入completion功能。但是这些你想要在动画之后完成。所以把它们放到completion函数中!像这样:

UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
        labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
        buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)
        // ... and everything else in the method goes here too
})


方法中的其他一切也需要移动到那里。 完成动画之后发生的所有事情都会进入completion函数。这就是completion的含义!

答案 1 :(得分:0)

将标签和按钮的超级视图clipsToBounds属性设置为true

UIView.animate(withDuration: 3, delay: 0.0, options: [], animations: {
        NSLog("Animation started")
        self.labelWinningPlayer.center = CGPoint(x: (self.labelWinningPlayer.center.x) * 3, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: (self.buttonNextGameLabel.center.x) * 3, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        NSLog("Animation stopped")
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
    })