gpt4 book ai didi

ios - Swift 中的无效定时器

转载 作者:行者123 更新时间:2023-11-29 05:13:48 25 4
gpt4 key购买 nike

我正在尝试在 Xcode 中创建一个应用程序。我有一个屏幕,每 30 秒切换一次标签,并且在 x 分钟后,将切换到显示“完成”的屏幕。还有一个返回原始 View 的按钮。目前,它在完成 x 分钟后卡住,并且不会切换到“完成”!屏幕。此外,如果我返回主视图然后再次尝试生成练习,计时器将倒计时 2 秒而不是 1 秒。

这是我的代码。任何提示将不胜感激!

import UIKit

var overallTime = minutes * 60
var timeLeft = 30
let resetTime = 30
var newE = true
var over = false

class ExerciseViewController: UIViewController {


@IBOutlet weak var time: UILabel!
@IBOutlet weak var progress: UIProgressView!
@IBOutlet weak var currExercise: UILabel!

let exercises = ["crunches", "bicycles", "leg lifts", "left crunches", "right crunches", "left cross crunches", "right cross crunches", "plank",
"penguins", "wipers", "scissors", "flutter kicks", "right leg climbs", "left leg climbs", "sit ups", "dead bugs", "russian twists", "toe touches",
"leg lifts with butt bump", "left plank", "right plank", "back plank", "alternating side sit-ups", "butterfly sit ups", "c-curve"]

var num = 0

var total = minutes * 2

var timer: Timer?

var bigtimer: Timer?

override func viewDidLoad() {
super.viewDidLoad()
resetView()
// Do any additional setup after loading the view.
pickExercise()
self.createTimer()
}

func pickExercise() {
let index = Int.random(in: 0 ..< exercises.count)
let curr = exercises[index]
currExercise.text = String(curr)
updateProgress()
num += 1
}

func updateProgress() {
let change: Float = Float(num) / Float(total)
self.progress.progress = change
}

func resetView() {
timer?.invalidate()
bigtimer?.invalidate()
timer = nil
bigtimer = nil
total = minutes * 2
num = 0
timeLeft = resetTime
overallTime = minutes * 60
}
}

extension ExerciseViewController {

@objc func updateTimer() {
if timeLeft <= 0 {
timeLeft = resetTime
time.textColor = UIColor.black
pickExercise()
if num > total {
time.text = ""
}
else {
time.text = String(timeLeft)
}
}
else {
timeLeft -= 1
if timeLeft <= 10 {
time.textColor = UIColor.red
}
if num > total {
time.text = ""
}
else {
time.text = String(timeLeft)
}
}

}

@objc func updateBigTimer() {
if overallTime <= 0 {
resetView()
performSegue(withIdentifier: "Completed" , sender: self)
}
else {
overallTime -= 1
}
}

func createTimer() {
// 1
if timer == nil {
// 2
timer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector: #selector(updateTimer),
userInfo: nil,
repeats: true)
}
if bigtimer == nil {
bigtimer = Timer.scheduledTimer(timeInterval: 1.0, target: self,
selector: #selector(updateBigTimer),
userInfo: nil,
repeats: true)
}
}
}

最佳答案

下面的“timer = Timer...”是故意的吗?或者错误地应该是“bigtimer = Timer...”?

if bigtimer == nil {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self,
selector: #selector(updateBigTimer),
userInfo: nil,
repeats: true)
}

因为第二次初始化“定时器”,它将删除第一个定时器的引用,但它会保持第一个定时器在没有引用的情况下运行。

关于ios - Swift 中的无效定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59398989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com