ios - 在快速平移滑动手势期间获取 y 坐标的最简单方法

标签 ios swift

我在滑动期间成功获取了x和y起始坐标:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let position :CGPoint = touch.locationInView(view)
        startX = Int(position.x)
        startY = Int(position.y)        
    }
}

我还需要滑动期间的 y 坐标。我已经成功地使用 UIPanGestureRecognizer 以一种非常迂回的方式做到了这一点。

必须有某种方法可以用尽可能少的行数来获取起始坐标。

有人能帮我指出正确的方向吗?

最诚挚的问候,尼克拉斯

最佳答案

您可以使用UIPanGestureRecognizer来实现此目的。它将为您提供滑动的 x 和 y 坐标。 Apple 专门为此场景创建了此功能 - 它比 TouchMoved 更容易实现并自行跟踪所有内容。

要设置手势识别器:

let gestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.someDraggableView.addGestureRecognizer(gestureRecognizer)

要获取翻译(在上面设置的回调中):

func handlePan(gestureRecognizer: UIPanGestureRecognizer) {
    if gestureRecognizer.state == .Began {
        // When the drag is first recognized, you can get the starting coordinates here
    }

    if gestureRecognizer.state == .Changed {
        let translation = gestureRecognizer.translationInView(self.view)  
        // Translation has both .x and .y values
    }
}

在回调的 .Changed 部分中,每次用户在给定 View 中移动手指时都会调用您的代码。您可以从 translation.y

获取 y 坐标

您可以查看更多示例here .

关于ios - 在快速平移滑动手势期间获取 y 坐标的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666712/

相关文章:

ios - 如何为 NSAttributedString 的背景设置圆角半径?

ios - StoryBoard.InstantiateViewController 给出 "Unknown class testController in Interface Builder file"

ios - 从给定范围和范围值 : Min= 0, Max= 999999 中找到剩余的 KM

swift - RxSwift 如何附加到 BehaviorSubject<[]>

ios - 在iOS swift中从后台扫描标签时在appDelegate中读取NFC标签UID

ios - 您可以并行运行 Xcuitests 吗?

ios - 混合应用程序 (cordova) 中的 IAP - iTunes 收据仅包含第一笔交易

ios - 在带有 Xcode 8 的 Objective C 中使用图表(BarChartDataEntry)iOS 库

swift - 如何在 Swift 2 的 UITextView 中将大型静态文本的某些部分设为粗体或斜体

ios - 为什么这些手势识别器中有四个可以工作? (向下不起作用)