Custom back button for NavigationView's navigation bar in SwiftUI

后端 未结 9 729
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 23:57

I want to add a custom navigation button that will look somewhat like this:

Now, I\'ve written a custom BackButton view for this. When applying

9条回答
  •  天命终不由人
    2020-11-30 00:24

    I found this: https://ryanashcraft.me/swiftui-programmatic-navigation/

    It does work, and it may lay the foundation for a state machine to control what is showing, but it is not a simple as it was before.

    import Combine
    import SwiftUI
    
    struct DetailView: View {
        var onDismiss: () -> Void
    
        var body: some View {
            Button(
                "Here are details. Tap to go back.",
                action: self.onDismiss
            )
        }
    }
    
    struct RootView: View {
        var link: NavigationDestinationLink
        var publisher: AnyPublisher
    
        init() {
            let publisher = PassthroughSubject()
            self.link = NavigationDestinationLink(
                DetailView(onDismiss: { publisher.send() }),
                isDetail: false
            )
            self.publisher = publisher.eraseToAnyPublisher()
        }
    
        var body: some View {
            VStack {
                Button("I am root. Tap for more details.", action: {
                    self.link.presented?.value = true
                })
            }
                .onReceive(publisher, perform: { _ in
                    self.link.presented?.value = false
                })
        }
    }
    
    struct ContentView: View {
        var body: some View {
            NavigationView {
                RootView()
            }
        }
    }
    
    If you want to hide the button then you can replace the DetailView with this:
    
    struct LocalDetailView: View {
        var onDismiss: () -> Void
    
        var body: some View {
            Button(
                "Here are details. Tap to go back.",
                action: self.onDismiss
            )
                .navigationBarItems(leading: Text(""))
        }
    }
    

提交回复
热议问题