How do you check if SwiftUI is in preview mode? How do you check if SwiftUI is in preview mode? ios ios

How do you check if SwiftUI is in preview mode?


You can detect this using ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"]. The value will be "1" at runtime when running in the canvas.


If you like me were looking for an environment variable to use in build scripts which xcode sets when building for SwiftUI previews, it turned out to be ENABLE_PREVIEWS.

SwiftUI were pausing preview when my script updated Info.plist file. To fix that I exit the script at certain point if we are in preview build.

if [ "${ENABLE_PREVIEWS}" = "YES" ]; then  exit 0;fi


I'm using SpriteKit and I'm setting preferredFramesPerSecond = 1 while I'm in preview mode, so that my computer doesn't white noise too much.

struct MyView: View {    var isPreview: Bool = false    var body: some View {        Text(isPreview ? "Preview" : "Not preview")    }}// Usagestruct MyView_Previews: PreviewProvider {    static var previews: some View {        return Group {            MyView(isPreview: true)            MyView(isPreview: false)        }    }}