Swift:UIPanGesture获取视图水平位置

时间:2018-06-22 10:28:27

标签: ios swift gesture

在照片上以垂直黑色显示的手势。

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

代码:

@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

2 个答案:

答案 0 :(得分:2)

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

在您的情况下,您似乎想将视图中的位置转换为屏幕,这就是您的关键窗口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

答案 1 :(得分:0)

您可以通过

获得积分
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
    }
}