ViewControllerに実装する
storyboardではなく、プログラムでEdgeスワイプを実装してみました。
UIScreenEdgePanGestureRecognizerをViewController.viewに追加して、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!")
- }
- }
- }
クラスに実装する
ViewControllerがファットになりそうなので、クラス化してみました。処理はほぼ同様で、selectorを新しく作成したSwipeLeftEdgePanGestureのメソッドを指定しています。
- 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!")
- }
- }
- }