gpt4 book ai didi

swift - NSTimer() - timer.invalidate 不适用于简单的秒表?

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:11 26 4
gpt4 key购买 nike

我有点不知所措,程序运行了,但是 timer.invalidate() 不起作用?欢迎任何提示。

我过去曾使用过这个程序并完成了它并且 timer.invalidate() 工作完美。我不认为这与我将它放入函数中这一事实有关,因为在我只是输入“timer.invalidate()”而不是“stop()”时它不起作用

每当我在 iOS 模拟器上单击取消按钮时,它只会将其重置回 0,但会继续计数。

提前致谢。

import UIKit

class ViewController: UIViewController {
var timer = NSTimer()
var count = 0
@IBOutlet weak var timeDisplay: UILabel!
@IBAction func playButton(sender: AnyObject) {
//play button
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}

@IBAction func resetTimer(sender: AnyObject) {
//cancel button
stop()
count = 0
timeDisplay.text = "0"
}


@IBAction func pauseButton(sender: AnyObject) {
stop()
}

func result() {
count++
timeDisplay.text = String(count)
}

func stop () {
timer.invalidate()
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

最佳答案

playButton() 中,您正在定义另一个 计时器,它不能从该函数外部失效 - 因此通过调用 timer.invalidate() 您只使 var timer = NSTimer() 无效,它不包含任何设置的计时器。

所以替换

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

关于swift - NSTimer() - timer.invalidate 不适用于简单的秒表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26797589/

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