[英]Nil cannot be assigned to type 'Timer'?
嗨,我正在完成一些有關阿爾茨海默氏病的研究-我希望能夠記錄完成繪圖所花費的時間(病人繪制只需幾秒鍾)。 我想記錄使用蘋果鉛筆在平板電腦上花費的時間以及完成繪圖所需的總體時間(在平板電腦上的時間加上筆划之間的時間)。
到目前為止,我已經創建了該應用程序,但無法使計時器正常工作。
我有繪畫/塗鴉板拍拍。
我嘗試了許多不同的方法,但是我只是缺乏足夠的代碼經驗,無法弄清楚為什么當蘋果鉛筆擊中數位板時它沒有啟動計時器。 下面的代碼用於ViewController腳本。
到目前為止,僅創建了=花時間的計時器之一。 但是我什至不能使它工作。
嘗試更改腳本,嘗試詢問朋友。 我很快就很陌生,因此不勝感激。
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值,您可以像這樣將timer對象設置為可選對象
var timer:Timer?
是的,這很有意義。 編輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.