不能将 Nil 分配给类型"计时器"?



嗨,我正在完成一些阿尔茨海默病的研究 - 我希望能够记录完成绘图所需的时间(患者只需几秒钟即可绘制)。我想记录在平板电脑上使用苹果铅笔所花费的时间以及完成绘图所花费的总时间(在平板电脑上的时间加上笔画之间的时间)。

到目前为止,我已经创建了此应用程序,但无法让计时器工作。

我有绘图/涂鸦板。

我已经尝试了许多不同的方法,但我在代码方面没有足够的经验来弄清楚为什么当苹果铅笔击中平板电脑时它没有启动计时器。下面的代码适用于视图控制器脚本。

到目前为止,只创建了一个 = 绘制所花费时间的计时器。但我什至无法让它工作。

尝试更改脚本,尝试询问朋友。我对 swift 很陌生,所以非常感谢任何帮助。


import UIKit
class ViewController: UIViewController {

@IBOutlet weak var canvasView: CanvasView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func clearCanvas(_ sender: Any) {
canvasView.clearCanvas()
timer.invalidate()
seconds = 0    
timeDrawing.text = "(seconds)"
}
@IBOutlet weak var timeDrawing: UILabel!
var seconds = 0 
var timer = Timer()
var isTimerRunning = false //This will be used to make sure only one timer is created at a time.
var resumeTapped = false
var touchPoint:CGPoint!
var touches:UITouch!
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
}
private(set) var from: Date?
@objc func updateTimer() {
let to = Date()
let timeIntervalFrom = (from ?? to).timeIntervalSince1970
let time = to.timeIntervalSince1970 - timeIntervalFrom
timeDrawing.text = "(round(time))" //This will update the label.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touch = touches.first else { return }
let touches = touch.location(in: canvasView) // or maybe ...(in: self)
if touch.type == .pencil  {
if !isTimerRunning {
from = Date()
runTimer()
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if !isTimerRunning {
timer.invalidate()
timer = nil
from = nil
timeDrawing.text = "0"
}
}
}

我希望当苹果铅笔碰到平板电脑时,它会启动计时器。然后,当铅笔离开平板电脑时,它将停止一个计时器并启动其中一个计时器(尚未实现)。(我还没有为两次冲程之间的时间添加另一个计时器,任何帮助也将不胜感激。

只有可选可以采用 nil 值,您可以像这样将计时器对象设置为可选

var timer:Timer?

是的,这是有道理的。编辑

最新更新