SwiftUI: How to present view when clicking on a button?

后端 未结 3 718
無奈伤痛
無奈伤痛 2020-12-05 01:45

I\'m trying to make an app using Apple\'s SwiftUI and I need to have two buttons that present two different views in a single List row.

3条回答
  •  青春惊慌失措
    2020-12-05 02:09

    Update: The NavigationButton was very short lived. In beta3 it is already deprecated. I am updating the code to use its replacement: NavigationLink.

    You can present a view from all three places. Here's how:

    import SwiftUI
    
    struct ContentView: View {
    
        var body: some View {
            NavigationView {
                TopView().navigationBarTitle(Text("Top View"))
            }
        }
    }
    
    struct TopView: View {
        @State private var viewTypeA = true
    
        let detailViewA = DynamicNavigationDestinationLink(id: \String.self) { data in
                ListA(passedData: data)
        }
    
        let detailViewB = DynamicNavigationDestinationLink(id: \String.self) { data in
                ListB(passedData: data)
        }
    
        var body: some View {
                List(0..<5) { item in
                    NavigationLink(destination: ListC(passedData: "FROM ROW #\(item)")) {
                        HStack {
                            Text("Row #\(item)")
                            Spacer()
                            Text("edit")
                                .tapAction {
                                    self.detailViewA.presentedData?.value = "FROM TAP ACTION Row #\(item)"
                            }
                        }
                    }
                }.navigationBarItems(trailing: Button(action: {
                                self.detailViewB.presentedData?.value = "FROM PLUS CIRCLE"
                }, label: {
                        Image(systemName: "plus.circle.fill")
                    }))
        }
    }
    
    struct ListA: View {
        let passedData: String
    
        var body: some View {
            VStack {
                Text("VIEW A")
                Text(passedData)
            }
        }
    }
    
    struct ListB: View {
        let passedData: String
    
        var body: some View {
            VStack {
                Text("VIEW B")
                Text(passedData)
            }
        }
    }
    
    struct ListC: View {
        let passedData: String
    
        var body: some View {
            VStack {
                Text("VIEW C")
                Text(passedData)
            }
        }
    }
    

提交回复
热议问题