swift - Nil 不能分配给类型 'Timer' 吗?

标签 swift ipad iso apple-pencil

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

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

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

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

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

尝试更改剧本,尝试询问 friend 。我对 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?

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

关于swift - Nil 不能分配给类型 'Timer' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57477428/

相关文章:

swift - Xcode:编译的应用程序文件无法像调试运行时一样工作

ios: mapkit 如何在 map 上启用当前位置按钮?

ios - iPad 应用程序左右两侧的空格

Python csv.reader 自动转换 ISO 日期?

iso - 什么是扩展 7 位(或 8 位)代码?

python - 在 Python 中解析 .iso 文件

ios - 如何在iOS中显示来自网络的pdf

ios - 选择 UITableViewCell 内的图像

ios - 网页抓取 Facebook 的最佳方式是什么

ios - 删除 iPad 分析数据