In an iOS app, I wanted to place the content view under the navigation bar like in ZStack, so that the content view does not shift when the navigation bar hides / shows.
XCode: 15.3
iOS: 15 or 16
Currently I have this code:
import SwiftUI
@main
struct ViewDismissApp: App {
var body: some Scene {
WindowGroup {
MyTabView()
}
}
}
struct MyTabView: View {
var body: some View {
TabView {
NavigationView {
RandomView(title: "tab 1")
}
.tabItem {
Text("Tab 1")
}
NavigationView {
RandomView(title: "tab 2")
}
.tabItem {
Text("Tab 2")
}
}
}
}
struct RandomView: View {
let title: String
var body: some View {
NavigationLink {
ChildView()
} label: {
Text(title)
}
}
}
struct ChildView: View {
@State private var showNavigationbar = true
@State private var hideTabbar = true
var body: some View {
mainBody()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background{Color.green}
.toolbar(hideTabbar ? .hidden : .visible, for: .tabBar)
.onAppear {
hideTabbar = true
}
.onDisappear {
hideTabbar = false
}
}
private func mainBody() -> some View {
VStack {
Text("Tap here to hide NavigationBar")
}
.onTapGesture(perform: {
showNavigationbar.toggle()
})
.navigationBarHidden(!showNavigationbar)
.navigationBarTitleDisplayMode(.inline)
.background{Color.yellow}
}
}
The ChildView
would visually move up and own when the navigation bar hides / shows. Like in this screenshot:
When the user tapped the text, the navigation bar hides and the content view extends upwards and the text moves up as well:
How can I make the content view (in green) extends beneath the navigation bar in the first place (i.e. always) ?