Skip to content

Instantly share code, notes, and snippets.

@Crysis21
Created October 14, 2024 10:38
Show Gist options
  • Save Crysis21/ccc0cc93e0349e399b5d85d5d4625db5 to your computer and use it in GitHub Desktop.
Save Crysis21/ccc0cc93e0349e399b5d85d5d4625db5 to your computer and use it in GitHub Desktop.
Enable Swipe To Back in SwiftUI by using an extension of the UINavigationController
//
// UINavigationController+TLDL.swift
// TLDL
//
// Created by Cristian Holdunu on 14.10.2024.
//
import UIKit
extension UINavigationController: @retroactive UIGestureRecognizerDelegate {
override open func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
interactivePopGestureRecognizer?.requiresExclusiveTouchType = true
interactivePopGestureRecognizer?.cancelsTouchesInView = true
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// Check if the other gesture recognizer is from a UIScrollView (like a horizontal pager)
if let scrollView = otherGestureRecognizer.view as? UIScrollView {
let touchLocation = gestureRecognizer.location(in: view)
// Check if the touch started within the first 50 points from the left edge
if touchLocation.x <= 50 {
// If the swipe started near the left edge, disable the scroll view’s pan gesture
scrollView.panGestureRecognizer.isEnabled = false
return true
} else {
// If the swipe didn't start near the edge, re-enable the scroll view’s pan gesture
scrollView.panGestureRecognizer.isEnabled = true
return false
}
}
return false
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Ensure the swipe-back gesture only triggers if the user starts the swipe within 50 points from the edge of the screen
let touchLocation = touch.location(in: view)
return touchLocation.x <= 50 // Allow the gesture only if the touch started within 50 points of the left edge
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment