1

拖动手指时,我将如何进行触摸移动查找距离。假设我的手指从 A 点开始,然后到达 10 像素的 B 点,然后返回到总共 20 像素的 A 点。我将如何计算?

4

5 回答 5

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 轴的差异之后,你可以得到差异

于 2012-11-02T06:34:29.627 回答
3

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)")
}
于 2017-10-11T18:59:17.967 回答
0

您可以跟踪用户移动的点。记住点touchesBegin:,累积距离,touchesMoved:得到整个距离touchesEnded:

– touchesBegan:withEvent:
– touchesMoved:withEvent:
- touchesEnded:withEvent:
于 2012-11-02T05:53:02.420 回答
0

为您的需求系统提供主要的 3 种委托方法,用于从设备屏幕获取触摸点,这 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)
}

我希望这对你有用...

于 2012-11-02T05:54:29.363 回答
0

到目前为止,所有答案都没有考虑多点触控。如果您需要记住哪个手指对应于哪个拖动以支持多点触控,这些解决方案会变得更加困难。

如果您只是对增量感兴趣,例如,您正在用两根手指同时滚动两个不同的东西,您可以直接从 中的触摸对象计算增量,touchesMoved而无需记住 中的任何状态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 }
于 2017-12-02T19:03:32.327 回答