我目前正在使用SwiftUI开发应用程序。
我可以成功构建这些代码,并且可以在模拟器中很好地工作。
但是当我在画布上看到代码的预览时,该预览不起作用,并且在下面出现错误消息:
Cannot preview in this file - My.app may have crashed
在这种情况下,如何解决此错误并在画布上查看预览?
以下是代码:
我看不到FirstView.swift和SecondView.swift的预览
ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
TabView {
FirstView()
.tabItem {
Text("First")
}.tag(1)
SecondView()
.tabItem {
Text("Second")
}.tag(2)
}
.environmentObject(viewModel)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
FirstView.swift
import SwiftUI
struct FirstView: View {
@EnvironmentObject var firstCheck: ViewModel
var body: some View {
VStack{
if firstCheck.check == true{
Text("checked")
}
}
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
SecondView.swift
import SwiftUI
struct SecondView: View {
@EnvironmentObject var secondCheck: ViewModel
var body: some View {
VStack{
Toggle(
isOn: $secondCheck.check
){
Text("change")
}
if self.secondCheck.check == true{
Text("checked")
}
}
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
ViewModel.swift
import Foundation
final class ViewModel: ObservableObject {
@Published var check: Bool = false
}
Xcode:版本11.7
Swift:Swift 5
答案 0 :(得分:1)
即使在预览中,您的视图也需要@EnvironmentObject
:
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
.environmentObject(ViewModel())
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
.environmentObject(ViewModel())
}
}