我想在移动设备上使用图表时跟踪手指,因此我使用UIResponder并覆盖touchBegan,touchMoved和touchEnded,如下所示。
var startLocation: CGPoint?
var totalDistance: CGFloat = 0
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
totalDistance = 0
startLocation = touch.location(in: self.chart1)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if let startLocation = startLocation, let touch = touches.first {
let currentLocation = touch.location(in: self.chart1)
let dX = currentLocation.x - startLocation.x
let dY = currentLocation.y - startLocation.y
self.totalDistance += sqrt(pow(dX, 2) + pow(dY, 2))
self.startLocation = currentLocation
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
print("Total distance: \(totalDistance)")
}
我构建了一个名为chart1的视图来呈现图表视图。我可以计算图表1外的空间距离。但是当我在图表上滑动时,我无法计算距离。 有人能给我一些建议吗? 任何帮助表示赞赏。