Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65871055/how-can-i-preview-a-swiftui-view-shared-between-ios-and-watchos

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
" + 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...