Push View programmatically in callback, SwiftUI

后端 未结 5 1659
长发绾君心
长发绾君心 2020-12-17 09:25

It seems to me that Apple is encouraging us to give up using UIViewController in SwiftUI, but without using view controlelrs, I feel a little bit powerless. Wha

5条回答
  •  孤街浪徒
    2020-12-17 09:58

    I'm adding some snippets here because I think it simplifies some things and makes reusing navigation links easier:

    1. Add View Navigation Extensions

    extension View {
        func navigatePush(whenTrue toggle: Binding) -> some View {
            NavigationLink(
                destination: self,
                isActive: toggle
            ) { EmptyView() }
        }
    
        func navigatePush(when binding: Binding,
                                       matches: H) -> some View {
            NavigationLink(
                destination: self,
                tag: matches,
                selection: Binding(binding)
            ) { EmptyView() }
        }
    
        func navigatePush(when binding: Binding,
                                       matches: H) -> some View {
            NavigationLink(
                destination: self,
                tag: matches,
                selection: binding
            ) { EmptyView() }
        }
    }
    

    Now, you can call on any view (make sure they (or a parent) are in a navigation view)

    2. Use at leisure

    struct Example: View {
        @State var toggle = false
        @State var tag = 0
    
        var body: some View {
            NavigationView {
                VStack(alignment: .center, spacing: 24) {
                    Text("toggle pushed me")
                        .navigatePush(whenTrue: $toggle)
                    Text("tag pushed me (2)")
                        .navigatePush(when: $tag, matches: 2)
                    Text("tag pushed me (4)")
                        .navigatePush(when: $tag, matches: 4)
    
                    Button("toggle") {
                        self.toggle = true
                    }
    
                    Button("set tag 2") {
                        self.tag = 2
                    }
    
                    Button("set tag 4") {
                        self.tag = 4
                    }
                }
            }
        }
    }
    

提交回复
热议问题