2

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

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

我把绘图/涂鸦板拍下来了。

我尝试了许多不同的方法,但我只是没有足够的代码经验来弄清楚为什么当苹果铅笔碰到平板电脑时它没有启动计时器。下面的代码用于 ViewController 脚本。

到目前为止,只创建了一个用于 = 绘制时间的计时器。但我什至无法让它发挥作用。

尝试更改脚本,尝试询问朋友。我对 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"
        }
}
}

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

4

1 回答 1

4

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

 var timer:Timer?

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

于 2019-08-13T14:47:47.203 回答