ios - 在不使应用程序崩溃的情况下循环生成随机数 Swift 2.2

标签 ios xcode swift

目前我正在写一个循环动画方法。此方法生成一个新的 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/

相关文章:

ios - Xcode和iOS版本匹配有什么意义?

ios - 显示一个空白的 UITableView

xcode - 在 XCode 中启用代码 View 的抗锯齿

ios - NSAttributedStringKey 给出未解析的标识符错误

ios - XCode 4.6显示了方法+(void)beginAnimations:(NSString *)animationID context:(void *)context的内存泄漏警告。

ios - Swift 以编程方式打开一个新的 View Controller

ios - 没有 phonegap 的 iOS 项目中的 JQuery Mobile

iOS 7 剪切、复制、全选 - 文本选项颜色

swift - 无法使用 Xib 将 UIView 类型的值转换为 [CustomView]

ios - 当节点下面的节点被删除时,节点不会移动