如何预览 iOS 和 WatchOS 之间共享的 SwiftUI 视图?

问题描述

我有一个示例 SwiftUI 视图,我在带有 Apple Watch 扩展的 iOS 中使用,当我尝试在 WatchOS“设备”中预览它时出现此错误

运行目标 iPhone 12 mini 对运行方案“TestApp WatchKit App”无效 我已经尝试了一切。像建议的 here 一样重新启动 Xcode 是第一件事。

解决方法

我最终让它“工作”的方式是固定预览。

这是我的示例视图,它位于“SharedViews”文件夹中,并且在 TestApp 和 TestApp WatchKit 扩展中有目标成员资格:

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)
//    }
//}

为了在 Watch 设备中预览此视图,我在 TestApp WatchKit 扩展中创建了一个“Helpers”文件夹,并在其中创建了一个“容器视图”,它只是 TestApp WatchKit 扩展的成员:

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

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

现在要预览我的 CustomTextView,我打开 ..Preview 文件并固定它的预览。然后我切换回 CustomTextView 文件,应用我的更改并在固定预览中查看它们。为了摆脱“无法预览...”错误,我像上面一样注释掉了自己的 CustomTextView 预览。

要在 iPhone 中预览,我更改了运行目标,取消注释自己的预览并取消固定观看预览。

有人有更好的解决方案吗?也许我可以同时在 iPhone 和 Apple Watch 中预览我的视图?