问题
I am developing a package of Swift Package Manager where SwiftUI views need to be included.
Every SwiftUI view should have a preview.
However, when I try to run a preview of any view I get the following error:
I found a way where if I change the package scheme to the main target scheme it becomes work. But using this way I have to switch between schemes all the time and the main target needs to be built every time I want to run a preview of a package.
Is it possible to run SwiftUI preview somehow directly from SPM Package without building the main target?
回答1:
Xcode 12
With Xcode 12 the SwiftUI Preview just works 'as-should' in standalone Package
Xcode 11+
Is it possible to run SwiftUI preview somehow directly from SPM Package without building the main target?
No, at least till now (Xcode 11.4beta3). Preview is a variant of Simulator and it needs UI executable to setup full-functional run-time context for your view preview.
Solution (from practice): setup SwiftUI executable target that in parallel contains all files from package (or package itself, depends) and perform all SwiftUI development it it, but package itself build during continuous integration process (including unit-testing).
回答2:
In Xcode 12 that has changed. Previews are enabled in Swift Packages. In fact, a lot of changes and new features were added that improve the user and developer experience for SwiftUI library extensions. You can watch this WWDC20 session to learn more.
To get it to work in the first beta of Xcode 12 you have to create a library Swift Package. Make sure you program can build - and that SwiftUI is imported. Also, remember to add the platforms supported in the package manifest - that are supported by SwiftUI and your package code. In the scheme selector select the library that you want to preview and a device supported by your library. After that enable the canvas the preview should be visible. There are currently some rough corners, but I hope errors and usability will improve on later versions.
来源:https://stackoverflow.com/questions/59732075/run-swiftui-preview-from-spm-package