NavigationView 与 NavigationLinks 替换屏幕的不同部分?

NavigationView with NavigationLinks replacing different part of the screen?

我正在尝试使用 SwiftUI 实现一个主视图(用于游戏),它在底部有一个广告横幅。当用户从主视图导航到设置视图时,相同的广告横幅应该保留在那里并继续显示广告。但是当用户从主视图导航到游戏视图时,横幅不应该可见。

我正在努力使用 NavigationView 来实现它。根据我在视图层次结构中定位 NavigationView 的方式,所有 NavigationLink 要么将广告横幅留在原处,要么将其隐藏。我试过只使用一个 NavigationView,也试过两个不同的 NavigationView,包括嵌套的和非嵌套的,但似乎没有什么能正常工作...

a 下面有一个简单的代码片段,该代码片段不起作用,但可以为您提供一些帮助。这两个链接都在底部留下红色的“广告横幅”。如果我将“广告横幅”代码(Spacer 和 HStack)移到内部 VStack 中,那么两个链接都会转到没有广告的视图。

如何在同一视图中使用不同行为的 NavigationLinks,一个替换整个屏幕,另一个让广告在下方可见?

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            NavigationView {
                VStack {
                    NavigationLink(destination: Text("No Ads")) {
                        Text("Link to a view with no Ads") // How to make this link to hide the Ad below?
                    }
                    NavigationLink(destination: Text("Ad visible")) {
                        Text("Link to a view with same Ad visible") // This link works as expected
                    } // Try moving the Ad banner right under here to see the other beavior
                }
            }
            Spacer() // This below is the Ad banner 
            HStack {
                Spacer()
                Text("Ad is shown here")
                    .padding()
                Spacer()
            }
            .background(Color.red)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

您可以根据点击的导航 Link 显示广告横幅。

struct ContentView: View {
    @State var firstActive : Bool = false
    @State var secondActive : Bool = false

    var body: some View {
        VStack {
            NavigationView {
                VStack {
                    NavigationLink(destination: Text("No Ads"), isActive: self.$firstActive) {
                        Text("Link to a view with no Ads") // How to make this link to hide the Ad below?
                    }
                    NavigationLink(destination: Text("Ad visible"), isActive: self.$secondActive) {
                        Text("Link to a view with same Ad visible") // This link works as expected
                    } // Try moving the Ad banner right under here to see the other beavior
                }
            }
            
            if (secondActive || (!secondActive && !firstActive))
            {
                Spacer() // This below is the Ad banner
                HStack {
                    Spacer()
                    Text("Ad is shown here")
                        .padding()
                    Spacer()
                }
                .background(Color.red)
            }
        }
    }
}

使用在 NavigationLink 中用作绑定的两个状态将跟踪哪个 NavigationLink 处于活动状态。然后仅在非活动状态或仅第二个活动时显示广告横幅。