How can I preview a device in landscape mode in SwiftUI?
Solution 1
Xcode 13
Now you can preview in landscape mode with .previewInterfaceOrientation
modifier to make it landscapeLeft
or landscapeRight
.
⚠️ The following image from WWDC21 uses horizontal
and vertical
that is NOT available in Xcode 13 beta!
Old but not Useless method:
You can set the size to any landscape size you want for PreviewProvider
:
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 1024, height: 768))
// iPad Mini landscape size
}
}
This is iPad Mini
landscape mode size.
Update: Xcode detects the device associated to the preview from the selected simulator at the top left of the IDE and it and will apply the safe area as you expected for some iPads and iPhones landscape mode.
💡 Master-Detail Demo
struct ContentView: View {
var body: some View {
NavigationView {
Text("Master")
Text("Detail")
}
}
}
Also, you can play with these two modifiers as your needs:
.environment(\.horizontalSizeClass, .regular)
.environment(\.verticalSizeClass, .compact)
Solution 2
ContentView().previewLayout(PreviewLayout.fixed(width:568,height:320))
View - IOS screen dimensions for different devices
Solution 3
iOS 15 / Xcode 13
Starting from iOS 15 we can use previewInterfaceOrientation
:
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
.previewInterfaceOrientation(.landscapeRight)
}
}
Felipe Peña
Felipe Peña is an entrepreneur, musician and iOS developer, currently building and creating new mobile apps and businesses. With more than 8 years of experience in software development, he has been supported and financed by public and private entities such as Wayra (Teléfonica incubator) and CORFO (chilean government). When he’s not in front of his PC, he enjoys helping other startups and entrepreneurs, listening to new music or cooking.
Updated on June 06, 2022Comments
-
Felipe Peña almost 2 years
How can I preview a device in landscape mode in SwiftUI?
I just have a simple preview like this:
struct ContentView_Previews : PreviewProvider { static var previews: some View { ContentView() } }
-
Felipe Peña almost 5 yearsThanks. Best answer before Apple releases landscape mode.
-
rener172846 almost 5 yearsHope Apple will releases landscape mode asap
-
Steve Madsen over 4 yearsI disagree; the best answer today is that it can't be done. The fixed size won't respect safe areas (as mentioned), but also doesn't resize ancillary chrome, such as status, navigation and tab bars. Finally, on iPad it won't show master/detail views properly.
-
Mojtaba Hosseini over 3 yearsnow it's supporting safe area AND show master/detail as you can see in the demo @SteveMadsen and other +20 :)
-
David James over 3 yearsThis hack does not work for live previews.
-
George over 2 years@MojtabaHosseini The
.previewInterfaceOrientation
is now available in the RC.