目前我正在写一个循环动画方法。此方法生成一个新的 arc4random_uniform,然后将其转换为 CGFloat。然后将这些值插入到 animateWithDuration 函数中:
func randomAnimationForPostPackets() {
while true {
let randomCoordinatesXInt: UInt32 = arc4random_uniform(300)
let randCoordsX = CGFloat(randomCoordinatesXInt)
let randomCoordinatesYInt: UInt32 = arc4random_uniform(300)
let randCoordsY = CGFloat(randomCoordinatesYInt)
UIView.animateWithDuration(5, delay: 0, options: [.AllowUserInteraction], animations: {
self.postPacketView.center.x = randCoordsX
self.postPacketView.center.y = randCoordsY
}, completion: nil)
}
}
当尝试在 while 循环中循环此函数时,应用程序会由于不断生成随机数而崩溃。我如何能够每次都基于一组新的随机坐标实现循环动画?
最佳答案
使用 while
循环只会尽可能快地调用动画,使用所有 CPU,最终会耗尽内存。
animateWithDuration
有一个 completion
闭包,在动画完成时调用。使用它来设置下一个动画。
func randomAnimationForPostPackets() {
let randomCoordinatesXInt: UInt32 = arc4random_uniform(300)
let randCoordsX = CGFloat(randomCoordinatesXInt)
let randomCoordinatesYInt: UInt32 = arc4random_uniform(300)
let randCoordsY = CGFloat(randomCoordinatesYInt)
UIView.animateWithDuration(5, delay: 0, options: [.AllowUserInteraction], animations: {
self.postPacketView.center.x = randCoordsX
self.postPacketView.center.y = randCoordsY
}) { (finished) in
self.randomAnimationsPostPacket()
}
}
关于ios - 在不使应用程序崩溃的情况下循环生成随机数 Swift 2.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154570/