Enhancing SwiftUI Navigation: A Guide to Disabling Interactive Pop Gesture

SwiftUI, Apple’s modern declarative framework, has revolutionized the way developers create intuitive and interactive apps. While SwiftUI provides a wealth of tools for crafting delightful user experiences, there are times when we want more control over certain aspects of navigation behavior.

Ahmed Yamany
2 min readDec 22, 2023

In this post, we’ll explore a simple yet powerful extension that allows you to fine-tune the interactive pop gesture in SwiftUI navigation controllers. Whether you want to temporarily disable or enable the swipe-to-go-back feature, this extension has got you covered.

The Challenge

SwiftUI’s navigation controllers come with a built-in interactive pop gesture, allowing users to navigate back by swiping from the left edge of the screen. However, there are scenarios where you might want to programmatically control this behavior.

The Solution: NavigationPopGestureDisabler

extension UIView {
var parentViewController: UIViewController? {
sequence(first: self) {
$0.next
}.first { $0 is UIViewController } as? UIViewController
}
}
private struct NavigationPopGestureDisabler: UIViewRepresentable {
let disabled: Bool

func makeUIView(context: Context) -> some UIView { UIView() }

func updateUIView(_ uiView: UIViewType, context: Context) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) {
uiView
.parentViewController?
.navigationController?
.interactivePopGestureRecognizer?.isEnabled = !disabled
}
}
}
public extension View {
@ViewBuilder
func navigationPopGestureDisabled(_ disabled: Bool) -> some View {
background {
NavigationPopGestureDisabler(disabled: disabled)
}
}
}

How It Works

The code introduces a UIViewRepresentable structure named NavigationPopGestureDisabler. This structure takes a boolean parameter, disabled, indicating whether the interactive pop gesture should be enabled or disabled.

By incorporating this structure into your SwiftUI views using the navigationPopGestureDisabled extension, you gain the ability to dynamically control the interactive pop gesture. The extension creates a background view using NavigationPopGestureDisabler, ensuring that the gesture behavior is applied consistently across your SwiftUI hierarchy.

Implementation Example

struct ContentView: View {
var body: some View {
NavigationView {
VStack {
// Your content here

}
.navigationPopGestureDisabled(/* Set to true or false based on your requirements */)
}
}
}

Feel free to integrate this extension into your SwiftUI projects and explore the endless possibilities it opens up for enhancing navigation control. Happy coding!

--

--

Ahmed Yamany
Ahmed Yamany

Written by Ahmed Yamany

I'm dedicated and passionate, seeking new challenges to extend my expertise

No responses yet