skip to Main Content

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.

enter image description here

Thank you in advance! The Lord Always Delivers!

2

Answers


  1. Seems you cannot do that with the new Preview Macro at this moment. One solution would be to use traits parameter and pass the value fixedLayout(width:height:) and provide the screen bound of the device you’re looking for:

    #Preview(traits: .fixedLayout(width: 375, height: 667)) {
        ContentView()
    }
    
    #Preview {
        ContentView()
    }
    

    You can write multiple Previews simultaneously like above. It will create 2 separate preview windows

    Login or Signup to reply.
  2. I found this in the Xcode 15 release notes:

    The preview canvas has a new control for picking which device to use for previewing. By default it tracks the device family of the selected run destination, but a specific device can be selected. This should be used in favor of the previewDevice modifier.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search