Reputation: 77
I am trying to implement with SwiftUI a main view (for a game), which has an ad banner at the bottom. When the user navigates from main view to the settings view, the same ad banner should stay there and keep showing the ad. But when the user navigates from the main view to the gameplay view, the banner should not be visible.
I am struggling to implement this with NavigationView. Depending on how I position the NavigationView in the view hierarchy, all the NavigationLinks either leave the ad banner in place or hide it. I have tried to use one NavigationView only and also played around with two different NavigationViews, both nested and non-nested, but nothing seems to work properly...
Below a there is a simple code snippet which does not work, but gives you something to work on. Both of the links leave the red "Ad banner" at the bottom. If I move the "Ad banner" code (Spacer and HStack) inside the inner VStack, then both of the links go to a view with no ad.
How to have differently behaving NavigationLinks in a same view, where one replaces the whole screen and the other leaves the ad visible below?
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()
}
}
Upvotes: 1
Views: 776
Reputation: 8547
You can show the Ad Banner depending on which Navigation Link was clicked.
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)
}
}
}
}
Using two States which are used as Binding in NavigationLink will keep track which NavigationLink is active. Then only show the Ad Banner when non is active or only the second one.
Upvotes: 1