Swift: UIPanGesture 获取视图的水平位置

Swift: UIPanGesture get location horizontally of view

ja 在照片中垂直黑色视图上的手势。

我想知道它在屏幕级别的位置,因为我想执行一个功能,例如,我将视图向右滑动到屏幕中心的一半以上

代码:

@objc func detectPan(recognizer: UIPanGestureRecognizer) {

    switch recognizer.state {
    case .began:
        self.startingConstant = self.centerConstraint.constant
    case .changed:
        let translation = recognizer.translation(in: self.view)
        self.centerConstraint.constant = self.startingConstant - translation.x

    default:
        break
    }
}

Fist image

Second image

您可以在视图之间转换坐标(点和框架),只要它们位于同一层次结构中即可。您有两种方法 convert(:to:)convert(:from:).

在您的情况下,您似乎想将视图中的位置转换为屏幕,这是您的关键 window UIApplication.shared.keyWindow

所以通常屏幕上的点是 let pointOnScreen = myView.convert(pointInMyView, to: UIApplication.shared.keyWindow)

所以在你的情况下:

let myView = self.view
let pointInMyView = recognizer.locationInView(myView)
let pointOnScreen = myView.convert(pointInMyView, to: UIApplication.shared.keyWindow)

let isViewGestureOnRightSideOfTheScreen = pointOnScreen.x > UIApplication.shared.keyWindow!.frame.midX

你可以通过

获得积分
func transform(for translation : CGPoint) -> CGAffineTransform {
        let moveBy = CGAffineTransform(translationX: translation.x, y: translation.y) 
        return moveBy
    }

@IBAction func setPanGesture(_ sender: UIPanGestureRecognizer) {
    switch sender.state {
    case .changed:
                let translation = sender.translation(in: view)
                let translationView = transform(for: translation)
                print(translationView)
    case .ended:
               let translation = sender.translation(in: view)
               let translationView = transform(for: translation)
               print(translationView)
    default:
            break
    }
}