ios 在SwiftUI中导航到根屏幕时创建多个后退按钮

kx1ctssn  于 2023-01-27  发布在  iOS
关注(0)|答案(1)|浏览(181)

假设我在SwiftUI中创建了3个屏幕,其中包含指向下一个屏幕的NavigationLink。例如,第一个屏幕导航到第二个屏幕。第二个屏幕导航到第三个屏幕。第三个屏幕导航到第一个屏幕。在这种情况下,即使我只使用了一次NavigationView(在第一个屏幕中)。当我从第三个屏幕导航到第一个屏幕时,我遇到了一个后退按钮。从那时起,当我开始导航时,它一直在增加。我曾尝试使用.navigationBarBackButtonHidden(true)。它隐藏了它,但后退按钮占用的空间仍然存在。我的代码类似于以下代码:

struct FirstScreen: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: SecondScreen()) {
                    Text("Go to Second Screen")
                }
            }
        }
    }
}

struct SecondScreen: View {
    var body: some View {
        VStack {
            NavigationLink(destination: ThirdScreen()) {
                Text("Go to Third Screen")
            }
        }
    }
}

struct ThirdScreen: View {
    var body: some View {
        VStack {
            NavigationLink(destination: FirstScreen()) {
                Text("Go to First Screen")
            }
        }
    }
}

this is the image

06odsfpq

06odsfpq1#

您正在将FirstScreen推送到导航堆栈中,但是FirstScreen包含它自己的NavigationView。如果您真的想继续将它们推送到堆栈中,请将NavigationView移到FirstScreen之外。

struct ContentView: View {
    var body: some View {
        NavigationStack { // Use NavigationStack for iOS 16
            FirstScreen()
        }
    }
}

struct FirstScreen: View {
    var body: some View {
        VStack {
            NavigationLink(destination: SecondScreen()) {
                Text("Go to Second Screen")
            }
        }
    }
}

如果你真的想把所有的视图从栈中弹出并返回到FirstScreen,你应该使用

init(path: Binding<NavigationPath>, etc)

下面是一个简单的示例,将path向下传递到堆栈,并将其重置为弹出回根...

enum Screen {
    case two, three
}

struct ContentView: View {
    
    @State var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            VStack {

                // value gets appended to path
                NavigationLink("Go to Second Screen", value: Screen.two)
            }

            // Decides which screen to show for values in path
            .navigationDestination(for: Screen.self) { index in
                switch index {
                case .two:
                    SecondScreen(path: $path)
                case .three:
                    ThirdScreen(path: $path)
                }
            }
        }
    }
}

struct SecondScreen: View {
    @Binding var path: NavigationPath
    var body: some View {
        VStack {
            NavigationLink("Go to Third Screen", value: Screen.three)
        }
    }
}

struct ThirdScreen: View {
    @Binding var path: NavigationPath
    var body: some View {
        VStack {
            Button("Go to First Screen") {

                // reset the path to pop to root
                path = NavigationPath()
            }
        }
    }
}

相关问题