Remove back button text from navigationbar in SwiftUI

前端 未结 3 1606
清酒与你
清酒与你 2021-01-07 02:53

I\'ve recently started working in SwiftUI, came to the conclusion that working with navigation isn\'t really great yet. What I\'m trying to achieve is the following. I final

相关标签:
3条回答
  • 2021-01-07 03:32

    I have found a straightforward approach to remove the back button text using SwiftUI only, and keeping the original chevron.

    import SwiftUI
    
    struct ContentView: View {
      
      @Environment(\.presentationMode) var presentation
      
      var body: some View {
        VStack {
          // Your main view code here
        }
        .navigationBarBackButtonHidden(true)
        .navigationBarItems(leading: Button(action: { presentation.wrappedValue.dismiss() }) {
          Image(systemName: "chevron.left")
            .foregroundColor(.blue)
            .imageScale(.large)
        })
      }
    }
    
    0 讨论(0)
  • 2021-01-07 03:47

    So I actually ended up with the following solution that actually works. I am overwriting the navigation bar items like so

    .navigationBarItems(leading:
        Image("backButton")
            .foregroundColor(.blue)
            .onTapGesture {
                self.presentationMode.wrappedValue.dismiss()
        }
    )
    

    The only issue with this was that the back gesture wasn't working so that was solved by actually extending the UINavigationController

    extension UINavigationController: UIGestureRecognizerDelegate {
        override open func viewDidLoad() {
            super.viewDidLoad()
            interactivePopGestureRecognizer?.delegate = self
        }
    
        public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
            return viewControllers.count > 1
        }
    }
    

    Now it's looking exactly the way I want it, the solution is kinda hacky... but it works for now, hopefully SwiftUI will mature a little bit so this can be done easier.

    0 讨论(0)
  • 2021-01-07 03:56

    Standard Back button title is taken from navigation bar title of previous screen.

    It is possible the following approach to get needed effect:

    demo

    struct TestBackButtonTitle: View {
        @State private var hasTitle = true
        var body: some View {
            NavigationView {
                NavigationLink("Go", destination:
                    Text("Details")
                        .onAppear {
                            self.hasTitle = false
                        }
                        .onDisappear {
                            self.hasTitle = true
                        }
                )
                .navigationBarTitle(self.hasTitle ? "Master" : "")
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题