I'm currently developing an application using SwiftUI.
I can build these codes successfully and these work well in a simulator.
But when I see a preview of the code on a canvas, the preview doesn't work, and there is an error message below:
Cannot preview in this file - My.app may have crashed
In this case, How can I solve this error and see the preview on the canvas?
Here are the codes:
I can't see previews of FirstView.swift and 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: Version 11.7
Swift: Swift 5