[英]Loop Random Number Generation Without Crashing Application Swift 2.2
目前,我正在編寫循環動畫方法。 此方法生成一個新的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()
}
}
@ Paulw11基本上在注釋中添加了它:您對animateWithDuration的調用是異步的,即它並沒有“阻塞”您的循環5秒鍾。 您的循環正在以最快的速度旋轉,例如惡作劇數以十億計次,甚至第一次機會都沒有出現。 實際上,我懷疑您的循環正在占用所有資源,以至於動畫從未嘗試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.