Search code examples
iosswiftgesture

Swift: UIPanGesture get location horizontally of view


ja a gesture that is on the view that vertical black in the photo.

I want to know its location at the level of the screen, because I want to execute a function if for example I slide the view to the right at more than half of the center of the screen

code:

@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


Solution

  • You can convert coordinates (points and frames) between views as long as they are on the same hierarchy. You have two methods convert(:to:) and convert(:from:).

    In your case you seem to want to convert location in your view to screen which is your key window UIApplication.shared.keyWindow.

    So in general the point on screen is let pointOnScreen = myView.convert(pointInMyView, to: UIApplication.shared.keyWindow).

    So in your case:

    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