我一直在研究以前的问题,但是,它们似乎已经过时或不适用于我的情况。在我的应用程序中,我想通过另一个变量(cps)每秒钟增加一个变量(money)。当我尝试进行永久循环或使用计时器时,出现错误或什么也没有发生。
class SecondViewController: UIViewController {
var money = 0
var cost = 20
var clicks = 1
var cost2 = 50
var CPS: Int = 0
var truth = true
@IBOutlet weak var costOutlet2: UILabel!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var cpsButtonOutlet: UILabel!
@IBOutlet weak var clicksButtonOutlet: UIButton!
@IBOutlet weak var clicksOutlet: UILabel!
@IBOutlet weak var cpsOutlet: UILabel!
@IBOutlet weak var scoreOutlet2: UILabel!
@IBOutlet weak var costOutlet: UILabel!
@IBOutlet weak var cpsBtnOutlet: UIButton!
override func prepare(for backsegue: UIStoryboardSegue, sender: Any?) {
let controller = backsegue.destination as! ViewController
controller.money = Int(scoreOutlet2.text!)!
controller.clicks = Int(clicksOutlet.text!)!
controller.CPS = Int(cpsOutlet.text!)!
controller.cost = Int(cost)
controller.cost2 = Int(cost2)
}
override func viewDidLoad() {
super.viewDidLoad()
costOutlet2.isHidden = true
costOutlet.isHidden = true
costOutlet.text = "\(cost)"
scoreOutlet2.text = "\(money)"
clicksOutlet.text = "\(clicks)"
cpsOutlet.text = "\(CPS)"
errorLabel.isHidden = true
clicksButtonOutlet.setTitle("$\(cost): +1 Clicks", for: .normal)
cpsBtnOutlet.setTitle("$\(cost2): +1 CPS", for: . normal)
}
override func viewDidAppear(_ animated: Bool) {
scoreOutlet2.text = "\(money)"
clicksOutlet.text = "\(clicks)"
}
@IBAction func addClicks(_ sender: Any) {
if (money >= cost) {
money = money - cost
scoreOutlet2.text = "\(money)"
cost = cost * 3
clicks = clicks + 1
clicksOutlet.text = "\(clicks)"
(sender as AnyObject).setTitle("$\(cost): +1 Clicks", for:[])
print(cost)
} else {
insufficent()
}
}
@IBAction func addCps(_ sender: Any) {
if (money >= cost2) {
money = money - cost2
scoreOutlet2.text = "\(money)"
cost2 = cost2 * 3
CPS = CPS + 1
cpsOutlet.text = "\(CPS)"
(sender as AnyObject).setTitle("$\(cost2): +1 CPS", for:[])
} else {
insufficent()
}
}
func insufficent() {
errorLabel.isHidden = false
errorLabel.text = "Insufficent Funds"
DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
self.errorLabel.isHidden = true
}
}
}
我目前正在尝试在Swift 4 Xcode 10上制作点击游戏,购买时我能够提高CPS,但是购买时,钱的价值不会每秒提高一次。无论“ CPS”的值是多少,如何使变量“ money”增加。
答案 0 :(得分:1)
尝试在viewController中使用代码
/...
override func viewDidLoad() {
super.viewDidLoad()
increaseMoneyEverySecond()
}
private func increaseMoneyEverySecond() {
money = money + CPS
DispatchQueue.main.asyncAfter(deadline: .now()+1) { [weak self] in
if let strongSelf = self {
strongSelf.increaseMoneyEverySecond()
}
}
}
/...