当我拖动手指时,我将如何进行触摸移动寻找距离。假设我的手指从A点开始,然后转到B点,这是10个像素,然后返回到A点,它们一起是20个像素。我该如何计算?
答案 0 :(得分:4)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
point1 = [touch locationInView:self];//(point2 is type of CGPoint)
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
point2 = [touch locationInView:self];//(point2 is type of CGPoint)
}
在CGPOint x或y轴的差异之后,你可以得到差异
答案 1 :(得分:2)
Swift中的整体解决方案:
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: view)
}
}
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: view)
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)")
}
答案 2 :(得分:0)
您可以跟踪用户已移动的点。请记住touchesBegin:
中的点,在touchesMoved:
中累积距离,并在touchesEnded:
中获得整个距离。
– touchesBegan:withEvent:
– touchesMoved:withEvent:
- touchesEnded:withEvent:
答案 3 :(得分:0)
为您的需求系统提供主要3委托方法从设备屏幕获取触摸点这三种方法是..
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@\"touchesBegan\");// here you can find out A point which user began to touch screen
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@\"touchesMoved\");// here get points of user move finger on screen to start to end point
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@\"touchesEnded\");// here user end touch or remove finger from Device Screen means (B)
}
我希望这对你有用......
答案 4 :(得分:0)
到目前为止,所有答案都不考虑多点触控。如果您需要记住哪个手指对应哪个拖动以支持多点触控,那么这些解决方案会变得有点困难。
如果您只对deltas感兴趣,比如说,您使用两根手指同时滚动两个不同的东西,则可以直接从touchesMoved
中的触摸对象计算delta,并忘记记住任何状态在touchesBegan
,
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
let a = t.location(in: view)
let b = t.previousLocation(in: view)
let delta = b.y - a.y
doSomethingWithDelta()
}
}
例如,如果您想要上下移动一系列SKNode,
let nodesForFirstFinger = children.filter { $0.name == "firstGuys" }
let _ = nodesForFistFinger.map { $0.position.y += delta }