Ios 我应该把应该在后台运行的函数放在哪里-Swift 4
我有以下功能:Ios 我应该把应该在后台运行的函数放在哪里-Swift 4,ios,swift,Ios,Swift,我有以下功能: func rocketsGo(){ let randomNumber = Int(arc4random_uniform(8)) self.rocket1.isHidden = true if randomNumber % 2 == 0 { if 0 == 0{ self.rocket1.isHidden = false let xPosR = rocket1.frame.origin.x
func rocketsGo(){
let randomNumber = Int(arc4random_uniform(8))
self.rocket1.isHidden = true
if randomNumber % 2 == 0 {
if 0 == 0{
self.rocket1.isHidden = false
let xPosR = rocket1.frame.origin.x + 500
let yPosR = rocket1.frame.origin.y
let heightCharacterR = rocket1.frame.size.height
let widthCharacterR = rocket1.frame.size.width
UIView.animate(withDuration: 1.75, animations: {
self.rocket1.frame = CGRect(x: xPosR, y: yPosR
, width: widthCharacterR, height: heightCharacterR)
}) { (finished) in
}
self.rocket1.isHidden = true
self.rocket1.frame = CGRect(x: xPosR - 500, y: yPosR, width: widthCharacterR, height: heightCharacterR)
基本上,它所做的就是把火箭从屏幕的一边移动到另一边,如果随机数是偶数,那么有时火箭移动,有时不移动
我希望这个功能总是在后台运行,因为我的应用程序背后的整个想法有时是火箭移动,有时不是。
我应该把函数放在哪里,以便它可以在后台运行
源代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var TheCharacter: UIImageView!
@IBOutlet weak var rocket1: UIImageView!
func rocketsGo(){
let randomNumber = Int(arc4random_uniform(8))
self.rocket1.isHidden = true
if randomNumber % 2 == 0 {
if 0 == 0{
self.rocket1.isHidden = false
let xPosR = rocket1.frame.origin.x + 500
let yPosR = rocket1.frame.origin.y
let heightCharacterR = rocket1.frame.size.height
let widthCharacterR = rocket1.frame.size.width
UIView.animate(withDuration: 1.75, animations: {
self.rocket1.frame = CGRect(x: xPosR, y: yPosR
, width: widthCharacterR, height: heightCharacterR)
}) { (finished) in
}
self.rocket1.isHidden = true
self.rocket1.frame = CGRect(x: xPosR - 500, y: yPosR, width: widthCharacterR, height: heightCharacterR)
}
}
我没有理由认为您将使用函数生成随机数,但有一种方法可以在Swift中创建一个生成随机数的变量: 让randomNumber=nsuid.uuidString
这将始终生成一个随机数。我会使用它作为常量,这样你可以随时调用它。希望这对你和其他人都有帮助 以下是一些操场代码,可以满足您的要求:
import UIKit
import PlaygroundSupport
func printRandomInBackground() {
DispatchQueue.global(qos: .background).async {
let min : UInt32 = 1
let max : UInt32 = 100
let randomNumber = arc4random_uniform(max - min) + min
print("\(randomNumber)")
}
}
printRandomInBackground()
PlaygroundPage.current.needsIndefiniteExecution = true
请记住,如果要更新UI,则需要切换到主线程
DispatchQueue.main.async {
// Update UI stuff here
}
您不能在后台运行rocketGo函数。用户界面更新必须始终在主队列上完成
听起来你只是想让rocketGo被一遍又一遍地叫唤。有几种方法可以做到这一点
您可以创建一个具有适当间隔的计时器,并在每次计时器触发时调用rocketGo
或者,您也可以在rocketGo函数中从视图动画的完成块调用rocketGo。但是,当随机数为奇数时,您需要一种触发rocketGo的方法。您能给出完整的代码吗?我正在Xcode中的一个游戏中尝试这样做。问题已经澄清。请更新或删除您的答案。问题已澄清。请更新或删除您的答案。