Custom back button with SwiftUI

Hello,

I'm trying to remove the current back button behavior in a navigation view and instead have a simple arrow.

Disabling the button with navigationBarBackButtonHidden and then adding my own with navigationBarItems works, but then I lose the swipe gesture to go back. I could try to rebuild this swipe gesture, but that seems hard to get the same feel, and it will most likely break often.

Is there something simpler ?

I'd be satisfied with just removing the text of the back button and keeping only the <.

Thanks
I don't think this is available in SwiftUI yet.
Your only other option is adding your own button and using a DragGesture.
Right now there's no simple way to do this. Here's a somewhat hackey solution.

create a GestureState at the top of your view
Code Block
@GestureState private var dragOffset = CGSize.zero

then add this to whatever you want to enable swipe-to-go-back functionality on!
Code Block Swift
Group {
Text("The entire View I want to enable swipe-to-go-back functionality on")
}
.gesture(DragGesture().updating($dragOffset, body: { (value, state, transaction) in
if(value.startLocation.x < 20 &&
value.translation.width > 100) {
self.presentationMode.wrappedValue.dismiss()
}
})

good luck!
The answer from @theSwolEnchilada didn't work for me, and as yet no other solutions found in searching various forums has worked for me using Xcode 12.3

This seems like a very common question among developers and it would be awesome if a simple & effective solution was offered in SwiftUI
@theSwolEnchilada's answer worked for me. Thanks for great support.
@theSwolEnchilada's solution worked fine for me. I'm using 14.5
Try to add this extension. I use it with the Navigation Bar hidden and it works just magically :)
Code Block language
extension UINavigationController: UIGestureRecognizerDelegate {
    override open func viewDidLoad() {
        super.viewDidLoad()
        interactivePopGestureRecognizer?.delegate = self
    }
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return viewControllers.count > 1
    }
}


10

This looks like a complete magic, but it works, i use Xcode Version 14.0 beta 2 (14A5229c), tested on IOS 14.1, 14.5, 15 and 16. This line obviously is a hack, but i don't care, to be honest :) interactivePopGestureRecognizer?.delegate = self

Xcode 14.3, this is still magically the fix. Thanks DanDolog!

Works on Xcode 15 beta 5. There should be a simpler way of doing this 🙂.

On iOS 17, view freeze when dismiss and try navigate or dismiss again.

Custom back button with SwiftUI
 
 
Q