gpt4 book ai didi

ios - 无法使计时器 swift 失效

转载 作者:行者123 更新时间:2023-11-28 12:17:59 30 4
gpt4 key购买 nike

在我的应用程序中,我应该使用多个计时器,但我不想为每个函数添加单独的计时器,我如何创建一个函数来简化创建多个计时器的过程,我尝试了下面的这段代码,它可以工作,但我不能使计时器无效。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var first: UILabel!

@IBOutlet weak var second: UILabel!

var count = 0
var count2 = 0

var timer = Timer()
var timer2 = Timer()

override func viewDidLoad() {
super.viewDidLoad()

timerWithDifferentIntervals(myTimer: timer, interval: 1, target: self, selector: #selector(handle1), userInfo: nil, repeats: true)

timerWithDifferentIntervals(myTimer: timer2, interval: 1/6, target: self, selector: #selector(handle2), userInfo: nil, repeats: true)
}

func handle1() {
count += 1
first.text = "\(count)"
}

func handle2() {
count2 += 1
second.text = "\(count2)"
}


func timerWithDifferentIntervals(myTimer: Timer, interval: TimeInterval, target: Any, selector: Selector, userInfo: Any?, repeats: Bool) {
var timers = myTimer
timers = Timer.scheduledTimer(timeInterval: interval, target: target, selector: selector, userInfo: userInfo, repeats: repeats)
}


@IBAction func stop(_ sender: UIButton) {
timer.invalidate()
timer2.invalidate()
}

}

最佳答案

您实际上从未为变量分配新值。您创建的计时器不会保存在任何地方,因此您无法使它们失效。

我建议进行以下更改:

var timer: Timer? {
didSet {
oldValue?.invalidate()
}
}
var timer2: Timer? {
didSet {
oldValue?.invalidate()
}
}

这将确保在分配新计时器时,前一个计时器始终无效。然后,您可以使用 timer = niltimer2 = nil 使之无效。

此外,您应该从您的方法中返回计时器:

func timerWithDifferentIntervals(interval: TimeInterval, target: Any, selector: Selector, userInfo: Any?, repeats: Bool) -> Timer {
return Timer.scheduledTimer(timeInterval: interval, target: target, selector: selector, userInfo: userInfo, repeats: repeats)
}

并按以下方式使用它:

timer = timerWithDifferentIntervals(interval: 1, target: self, selector: #selector(handle1), userInfo: nil, repeats: true)

虽然现在这个方法基本上什么都不做,所以也没有必要了

关于ios - 无法使计时器 swift 失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45797092/

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