How can I preview a SwiftUI View shared between iOS and WatchOS?

788 Views Asked by At

I have a sample SwiftUI View I am using in a iOS with Apple Watch Extension and I am getting this error when I try to preview it in a WatchOS "Device":

The run destination iPhone 12 mini is not valid for Running the scheme 'TestApp WatchKit App' I have tried everything. Restarting Xcode like suggested here was one of the first things.

1

There are 1 best solutions below

0
On BEST ANSWER

The way I got it to "work" eventually was with a pinned preview.

This is my sample View, it lives in a "SharedViews" Folder and it has Target Membership in TestApp as well as TestApp WatchKit Extension:

struct CustomTextView: View {
    let caption: String
    let foreground: Color
    var body: some View {
        VStack {
            Text(caption)
                .padding()
            Text("Colored\r" + caption)
                .foregroundColor(foreground)
                .padding()
        }
    }
}

//struct CustomTextView_Previews: PreviewProvider {
//    static var previews: some View {
//        CustomTextView(caption: "Shared Preview", foreground: .blue)
//    }
//}

To preview this View in a Watch Device I created a "Helpers" Folder in TestApp WatchKit Extension and inside this I created a "Container View" which is only Member of TestApp WatchKit Extension:

struct CustomTextViewWatchPreview: View {
    var body: some View {
        CustomTextView(caption: "Watch Preview Container", foreground: .red)
    }
}

struct CustomTextViewWatchPreview_Previews: PreviewProvider {
    static var previews: some View {
        CustomTextViewWatchPreview()
    }
}

Now to preview my CustomTextView I open the ..Preview File and pin it's preview. Then I switch back to the CustomTextView file, apply my changes and see them in the pinned preview. To get rid of the "cannot preview..." error I comment-out the own preview of the CustomTextView like above.

To preview in iPhone I change the run target, uncomment the own preview and unpin the Watch Preview.

Does anyone have a better solution? Maybe one where I can preview my View in iPhone and Apple Watch at the same time?