I am trying to figure out why rotating the device makes the content go away.
This is the exact code I am running:
struct ContentView: View {
@State private var selection = 0
init() {
}
var body: some View {
NavigationView {
VStack {
Button(action: {
}) {
Text("Tap me")
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
}.shadow(color: Color.blue, radius: 20, y: 5)
.frame(width: 300, height: 100, alignment: .trailing)
Text("SwiftUI")
.navigationBarTitle("Nav Title")
}
Color.red.edgesIgnoringSafeArea([.top,.bottom,.leading,.trailing])
}
}
}
How can I fix this so rotating the device keeps content in view?
To provide more feedback after "Liem Vo" answer.
If I run the code on the iPhone 11 Pro, and not the max, it works.
When running it on the max, the "primary view" goes off screen to the left in landscape and it can be pulled in by swiping on it. I wasn't aware of this behavior using NavigationView in SwiftUI, so that's what got me.
Here's the behavior on the MAX without the fix suggested by "Liem Vo":
The problem is with the landscape mode the view is changed so you need to handle the view in a different mode.
Create an extension method as below
extension View {
func phoneOnlyStackNavigationView() -> some View {
if UIDevice.current.userInterfaceIdiom == .phone {
return AnyView(self.navigationViewStyle(StackNavigationViewStyle()))
} else {
return AnyView(self)
}
}
}
And use this method in your view.
struct ContentView: View {
@State private var selection = 0
var body: some View {
NavigationView {
VStack {
Button(action: {
}) {
Text("Tap me")
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
}.shadow(color: Color.blue, radius: 20, y: 5)
.frame(width: 300, height: 100, alignment: .trailing)
Text("SwiftUI")
.navigationBarTitle("Nav Title")
}
Color.red.edgesIgnoringSafeArea([.top,.bottom,.leading,.trailing])
}
.phoneOnlyStackNavigationView()
}
}
More detail you can refer from https://www.hackingwithswift.com/books/ios-swiftui/making-navigationview-work-in-landscape
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With