ios - 在 UILabel 上添加和删除动画

标签 ios objective-c iphone xcode swift

我正在创建一个英语打字游戏。单词从键盘的顶部到边缘。为了对我使用的标签的下落进行动画处理:

UIView.animateWithDuration(25, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {

 label.frame = CGRectMake(self.view.frame.width - (label.frame.origin.x+label.frame.width), self.view.frame.height-self.keyboardYPosition!, label.frame.width, width)

}){(success) in

label.removeFromSuperview()

for label in self.currentLabelsArray {
                    label.layer.removeAllAnimations()
                    label.removeFromSuperview()
                }
self.gameOver()


}

一切顺利。我面临的问题是:我在创建每个标签时调用这个动画 block 。实际上这个动画 block 位于一个名为 createLabels() 的函数中。使用 NSTimer 每 5 秒调用一次 createLabel 函数。游戏结束后,我会显示上面的 View ,并带有重新启动按钮。现在问题来了:

在游戏结束之前,我们可能已经创建了 3-4 个标签,并将其推送到动画 block 中。但第一个标签可能会结束游戏。我在其上方看到一个游戏结束 View ,并带有重新启动按钮。一旦我点击重新启动,我的游戏就会再次结束,因为之前创建的标签仍在调用 UIAnimation 的完成 block 。除非我的所有标签都完成了动画,否则我无法重新启动游戏。

有没有办法在游戏完成后移除动画,这样已经创建的标签就不会再进入完成 block ?

我使用以下代码从 View 中删除标签并删除其动画:

for label in self.currentLabelsArray {
                    label.layer.removeAllAnimations()
                    label.removeFromSuperview()
                }

最佳答案

一个快速的猜测是,也许您错过了使计时器对象无效的操作。

for label in self.currentLabelsArray {
    label.layer.removeAllAnimations()
    label.removeFromSuperview()
}
myTimer.invalidate();

因此计时器不会在 5 秒后调用 createLabels。游戏重新开始后重新安排时间。

希望对您有所帮助!

编辑:

另一个指针可能是清除标签数组。

self.currentLabelsArray.removeAllObjects();

调用self.gameOver() 当且仅当,队列中没有游戏结束请求。

编辑:

UIView.animateWithDuration(25, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {

 label.frame = CGRectMake(self.view.frame.width - (label.frame.origin.x+label.frame.width), self.view.frame.height-self.keyboardYPosition!, label.frame.width, width)

}){(success) in

//label.removeFromSuperview()

for label in self.currentLabelsArray {
     label.layer.removeAllAnimations()
     label.removeFromSuperview()
}

if(self.currentLabelsArray.count > 0) {
     self.currentLabelsArray.removeAllObjects()
     self.gameOver()
}

}

关于ios - 在 UILabel 上添加和删除动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454681/

相关文章:

ios - 如何在 VIPER 设计模式中将 ViewController Reference 传递给 Router?

ios - NSURLConnection如何获取剩余时间信息

ios - 如何为 UIImageView 设置特定大小

c++ - 如何将 std::cout 重定向到 UITextView?

ios - 带有静态链接的 libz dylib 不支持 iOS 7

iphone - NSMutableArray 的最小值和最大值

ios - AFNetworking 2.0 + UIProgressView 如何正确显示上传 session 的进度

ios - 解码 Storyboard时访问错误导致崩溃

iOS Location Services 访问和系统 Frequent Location

iphone - 页面控制点没有改变