如何解决无法在此文件中预览的问题?
Posted
技术标签:
【中文标题】如何解决无法在此文件中预览的问题?【英文标题】:How can I solve that cannot preview in this file? 【发布时间】:2020-09-03 14:33:11 【问题描述】:我目前正在使用 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
斯威夫特:斯威夫特 5
【问题讨论】:
【参考方案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())
【讨论】:
感谢您的帮助,现在预览效果很好!以上是关于如何解决无法在此文件中预览的问题?的主要内容,如果未能解决你的问题,请参考以下文章