最近我已经开始实现swiftUI
。想知道PreviewProvider
是什么吗?
与init()
一样吗?
谢谢。
答案 0 :(得分:1)
PreviewProvider
是用于生成预览的协议,您可以在Xcode的右侧看到该预览。
如您在图片中看到的,您具有此预览,但是仅在使用macOS Catalina时可见。当需要生成预览时,将调用实现该结构的结构。在您运行应用程序时未调用它。
您可以在Apple docs
中了解有关此协议的更多信息。答案 1 :(得分:0)
协议
一种在Xcode中生成视图预览的类型。
protocol PreviewProvider
Xcode会在您的应用程序中静态发现符合PreviewProvider协议的类型,并为其发现的每个提供程序生成预览。
它具有两个变量:
/// Generates a collection of previews.
static var previews: Self.Previews { get }
/// Returns which platform to run the provider on.
///
/// When `nil`, Xcode infers the platform based on the file the
/// `PreviewProvider` is defined in. This should only be provided when the
/// file is in targets that support multiple platforms.
static var platform: PreviewPlatform? { get }
以及相关类型:
/// The type of the previews variable.
associatedtype Previews : View
这就是我们所拥有的。
在文档中没有提到解释它们在发行模式下如何工作的内容。但是我在WWDC19中看到了,他们将预览放在DEBUG
内:
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
因此,我个人遵循这一原则,以确保在文档变得更加清晰之前,它们不会在发布模式下进行编译。