I couldn't find a way to preview my SwiftUI views on multiple devices using the new XCode 15's #Preview macro.
It was working with XCode 14 and was showing side-by-side previews on the canvas, each preview with the correct target device, but it's not the case with XCode 15, here's my code to do that:
struct ContentView: View {
var body: some View {
Text("Hello, world!")
}
}
#Preview {
ContentView()
.previewOnDevices()
}
//#Preview {
// ContentView()
// .previewOnDevices()
//}
extension View {
func previewOnDevices() -> some View {
ForEach(DeviceName.all, id: \.self) { devicesName in
previewDevice(PreviewDevice(rawValue: devicesName))
.previewDisplayName(devicesName)
}
}
}
enum DeviceName: String, CaseIterable {
//xcrun simctl list devicetypes
case iPhoneSE = "iPhone SE (3rd generation)"
case iPhone13Mini = "iPhone 13 mini"
static var all: [String] {
return DeviceName.allCases.map { $0.rawValue }
}
}
and the result is the same view repeated:

I am aware that I can choose any device I want from the devices list in the canvas but this shows me one device at a time, meaning that I need to choose the desired device each time I need it which's a headache, even if I have multiple #Previews, XCode sticks for the chosen device in the canvas among #Preview previews.
Any thoughts on this would be appreciated.
I've tried many things and done extensive research.
Here's my final conclusion: as of Xcode 15.1, there's no way to accomplish this using a #Preview macro.
You can find a similar answer here: https://stackoverflow.com/a/77386048/1823922.
In my view, this limitation likely exists for performance reasons. Currently, I've set up previews using the say old PreviewProvider method with three devices:
As result, I've noticed a much longer loading times when switching between previews and SwiftUI views specially.
Anyway, it can be done, but only like this:
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewOnDevices()
}
}
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