Ios 如何创建精度为0.1秒的计时器?

Ios 如何创建精度为0.1秒的计时器?,ios,swift,timer,Ios,Swift,Timer,我尝试在绘图应用程序中添加计时器,以便它可以跟踪绘图的时间。当用户开始绘图(触摸开始)时,计时器开始计时。然后,当用户提起笔或手指时,计时器停止。我希望计时器的精度为0.1秒 以下是我尝试过的代码,但只能将1作为最小的内部变量 @objc func startTiming () { time += 1.0 } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)

我尝试在绘图应用程序中添加计时器,以便它可以跟踪绘图的时间。当用户开始绘图(触摸开始)时,计时器开始计时。然后,当用户提起笔或手指时,计时器停止。我希望计时器的精度为0.1秒

以下是我尝试过的代码,但只能将1作为最小的内部变量

@objc func startTiming () {
         time += 1.0
     }
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    //start timing
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(TrailingCanvas.startTiming), userInfo: nil, repeats: true)
    let touch = touches.first
    startingPoint = touch?.preciseLocation(in: self)
    TrailUserInputX.append(startingPoint.x)
    TrailUserInputY.append(startingPoint.y)
    print("\(String(describing: touch?.force))")
    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    //timer
    timer.invalidate()
    endingPointX = TrailUserInputX.last
    if endingPointX != nil {
        UserMatchingLocation.append(endingPointX!)
    }
}
@objc func启动(){
时间+=1.0
}
覆盖func TouchesBegind(Touchs:Set,带有事件:UIEvent?){
//开始计时
timer=timer.scheduledTimer(时间间隔:0.1,目标:self,选择器:#选择器(TrailingCanvas.startTiming),userInfo:nil,repeats:true)
让我们先接触
启动点=触摸?精确定位(in:self)
TrailUserInputX.append(startingPoint.x)
trailUserInput.append(startingPoint.y)
打印(\(字符串(描述:touch?.force)))
}
}
覆盖函数touchesend(touchs:Set,带有事件:UIEvent?){
//计时器
timer.invalidate()
endingPointX=TrailUserInputX.last
如果endingPointX!=nil{
UserMatchingLocation.append(endingPointX!)
}
}

计时器不适合此工作。您可以在
触摸开始
处获得更精确的时间记录(作为
日期
对象),并在
触摸结束
中查看从现在起经过了多少时间

var lastTouchesBeganDate: Date?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    lastTouchesBeganDate = Date()

    let touch = touches.first
    startingPoint = touch?.preciseLocation(in: self)
    TrailUserInputX.append(startingPoint.x)
    TrailUserInputY.append(startingPoint.y)
    print("\(String(describing: touch?.force))")
    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    time += lastTouchesBeganDate?.timeIntervalSinceNow ?? 0

    endingPointX = TrailUserInputX.last
    if endingPointX != nil {
        UserMatchingLocation.append(endingPointX!)
    } }
var lastTouchesBeganDate:日期?
覆盖func TouchesBegind(Touchs:Set,带有事件:UIEvent?){
lastTouchesBeganDate=日期()
让我们先接触
启动点=触摸?精确定位(in:self)
TrailUserInputX.append(startingPoint.x)
trailUserInput.append(startingPoint.y)
打印(\(字符串(描述:touch?.force)))
}
}
覆盖函数touchesend(touchs:Set,带有事件:UIEvent?){
时间+=上次触摸开始?时间间隔自现在起??0
endingPointX=TrailUserInputX.last
如果endingPointX!=nil{
UserMatchingLocation.append(endingPointX!)
} }

不要使用计时器测量经过的时间。只需保存操作开始的日期,并在更新用户界面时检查日期时间间隔InceNow是否可以只执行
time+=0.1
?或者更好的方法是:忘记计时器,只需获取触摸开始的日期,然后获取触摸结束的日期,然后减去它们。