'SwiftUI view is in the middle instead of in the top - NavigationView
I am trying to create a navigation view in SwiftUI - I want to navigate from the login form to the Home Screen. In the preview, the Home Screen is looking how it should, but on the live preview - it is centered in the middle of the screen. I tried with .navigationBarHidden(true), it goes a little bit up, but still not on the top of the screen. Please help.
struct ContentView: View {
@EnvironmentObject var viewModel: AppViewModel
var body: some View {
NavigationView {
if viewModel.signedIn {
NavigationView {
HomeScreen()
}
.navigationBarHidden(true)
}
else {
SignInView()
}
}
.onAppear {
viewModel.signedIn = viewModel.isSignedIn
}
}
}
Solution 1:[1]
Add a VStack and Spacer. The spacer consumes the rest of the space below the HomeScreen
NavigationView {
VStack {
HomeScreen()
Spacer()
}
}
If SignInView is also supposed to be on top move the VStack and the Spacer up accordingly.
Solution 2:[2]
You need to "push" the view up by using a Spacer() inside a VStack:
var body: some View {
NavigationView {
// Add this
VStack {
if viewModel.signedIn {
NavigationView {
HomeScreen()
}
.navigationBarHidden(true)
}
else {
SignInView()
}
// This will push the view up
Spacer()
}
}
.onAppear {
viewModel.signedIn = viewModel.isSignedIn
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vadian |
| Solution 2 | HunterLion |
