尝试创建多屏幕流程时,SwiftUI“推送” NavigationView / NavigationLink不起作用

时间:2020-05-18 17:54:15

标签: swiftui

在SwiftUI中,我设置了4个屏幕流(1> 2> 3> 4),用户将在每个屏幕上单击“下一步”以导航到下一个屏幕,就像UIKit中的典型推流一样。我使用“程序化” NavigationLink(例如isActive参数)来提高灵活性。它进入屏幕3,但是由于某种原因,在屏幕3上单击下一步无法导航到屏幕4。无法弄清楚。

struct FlowView: View {
@State var navigateToScreen2 = false
@State var navigateToScreen3 = false
@State var navigateToScreen4 = false
var body: some View {
    NavigationView {
        VStack {
            Text("Screen 1")
            Button(action: { self.navigateToScreen2 = true }, label: { Text("Next") })
            NavigationLink(destination:
                VStack {
                    Text("Screen 2")
                    Button(action: { self.navigateToScreen3 = true }, label: { Text("Next") })
                    NavigationLink(destination:
                       VStack {
                            Text("Screen 3")
                            Button(action: { self.navigateToScreen4 = true}, label: { Text("Next") })
                            NavigationLink(destination:
                                Text("Screen 4"),
                                isActive: self.$navigateToScreen4,
                                label: { EmptyView() }
                            )
                        },
                        isActive: self.$navigateToScreen3,
                        label: { EmptyView() }
                    )
                },
                isActive: self.$navigateToScreen2,
                label: { EmptyView() }
            )
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

我会这样做。它可以工作,并且可以更好地阅读:

struct ContentView: View {

    @State private var navigateToScreen2 = false

    var body: some View {
        NavigationView {
            NavigationLink(destination: View2(), isActive: $navigateToScreen2) {
                Text("View1")
            }
        }
    }
}

struct View2: View {
    @State private var navigateToScreen3 = false

    var body: some View {
        NavigationLink(destination: View3(), isActive: $navigateToScreen3) {
            Text("View2")
        }
    }
}

struct View3: View {
    @State private var navigateToScreen4 = false

    var body: some View {
        NavigationLink(destination: View4(), isActive: $navigateToScreen4) {
            Text("View3")
        }
    }
}

struct View4: View {
    var body: some View {
        Text("View4")
    }
}