トラッキング コード

8/17/2019

How to use UIScreenEdgePanGestureRecognizer, via Swift Code

implement in UIViewController


I had implemented the screen edge swipe with using UIScreenEdgePanGestureRecognizer, without Storyboard.

We need to add edgePan to ViewController.view. if you want to handle the acton, you have to use #selector.

class ViewController: UIViewController {

    private let closer = SwipeEdgeCloser()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleScreenEdgeSwiped))
        edgePan.edges = .left
        view.addGestureRecognizer(edgePan)
    }

    @objc func handleScreenEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
        if recognizer.state == .recognized {
            print("Screen edge swiped!")
        }
    }
}



new class implemented Edge Swipe Gesture


If you do not like "fat UIViewController", you should new class implemented Edge Swipe Gesture.


class ViewController: UIViewController {

    private let closer = SwipeLeftEdgePanGesture()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addGestureRecognizer(closer.panGesture)
    }
}

final class SwipeLeftEdgePanGesture {
    let panGesture: UIScreenEdgePanGestureRecognizer
    
    init() {
        panGesture = UIScreenEdgePanGestureRecognizer()
        panGesture.edges = .left
        panGesture.addTarget(self, action: #selector(SwipeLeftEdgePanGesture.screenEdgeSwiped))
    }
    
    @objc private func screenEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
        if recognizer.state == .recognized {
            print("SwipeLeftEdgePanGesture: Screen edge swiped!")
        }
    }
}