There is a new #Preview
macro (or at least new to me). It’s discussed on the SwiftLee blog here. I’m excepting some of his code exampled below to ask my question.
To preview your code in the SwiftUI canvas you used to have to code:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World!")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
…but now (October 2023) you can code:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World!")
}
}
}
#Preview {
ContentView()
}
My question is: how do we re-code the following taking into account Apple’s #Preview
macro syntax so we can change the device-displayed-on-SwiftUI-LivePreview-Canvas programmatically:
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().previewDevice(PreviewDevice(rawValue: "iPhone SE"))
}
}
The work-around I see is a dropdown graphical interface on the canvas the lets you manually change the displayed device in the Canvas, but is there a way to programmatically do it.
Thank you in advance! The Lord Always Delivers!
2
Answers
Seems you cannot do that with the new Preview Macro at this moment. One solution would be to use
traits
parameter and pass the valuefixedLayout(width:height:)
and provide the screen bound of the device you’re looking for:You can write multiple Previews simultaneously like above. It will create 2 separate preview windows
I found this in the Xcode 15 release notes:
That is a rather strong message telling you not to use
previewDevice
, and use the control on the canvas GUI to select a preview device going forward.This is reasonable in my opinion. One should not preview on only a single device that they specify. Apps should work on various devices, and the code you write should not have a specific device associated with it.