获取 TasksView() 的“调用中缺少参数‘realmManager’的参数”错误
我尝试阅读 Realm 的文档,但根据代码,我认为没有任何问题?有东西不见了,但我不知道它是什么。
代码如下:
TasksView 文件 -
import SwiftUI
struct TasksView: View {
@Environment var realmManager: RealmManager
var body: some View {
VStack {
Text("Task List")
.font(.title3).bold()
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(hue: 0.086, saturation: 0.141, brightness: 0.901))
}
}
struct TasksView_Previews: PreviewProvider {
static var previews: some View {
TasksView()
.environmentObject(realmManager)
}
}
ContentView2 文件 -
import SwiftUI
struct ContentView2: View {
@StateObject var realmManager = RealmManager()
@State private var showAddTaskView = false
var body: some View {
ZStack(alignment: .bottomTrailing){
TasksView()
.environmentObject(realmManager)
SmallAddButton()
.padding()
.onTapGesture {
showAddTaskView.toggle()
}
}
.sheet(isPresented: $showAddTaskView) {
AddTaskView()
.environmentObject(realmManager)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
.background(Color(hue: 0.086, saturation: 0.141, brightness: 0.901))
}
}
struct ContentView2_Previews: PreviewProvider {
static var previews: some View {
ContentView2()
}
}
@Environment
与 environment
视图修饰符一起使用,并允许您读取 EnvironmentValues
的特定键路径的值。
你正在使用
environmentObject
来注入领域管理器,因为你想在视图之间共享领域管理器。您应该使用 @EnvironmentObject
来读取 environmentObject
修饰符的值,而不是 @Environment
.
像这样声明
realmManager
:
@EnvironmentObject var realmManager: RealmManager
我认为问题出在您在
realmManager
中的TaskView
声明中。每当您通过 @StateObject
将 environmentObject(_:)
传递给视图层次结构时,您在子视图中使用该对象的方式是用 @EnvironmentObject
包装一个变量,该变量具有您想要使用的所需对象类型,而不是 @Environment
.每种类型只能有一个环境对象,允许 SwiftUI 推断您的@EnvironmentObject
正在引用哪个对象。
例子:
@main
struct MemorizeApp: App {
// Create @StateObject
@StateObject var themeStore = ThemeStore()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(themeStore)
// Allow this same @StateObject to be used in all child views of
// ContentView, and ContentView itself, as an @EnvironmentObject.
}
}
}
struct ContentView: View {
// Don't need our @EnvironmentObject here
// yet, so we don't declare anything.
var body: some View {
ThemeChooser()
}
}
struct ThemeChooser: View {
// ThemeChooser is a descendent of ContentView and thus we
// can use our @EnvironmentObject of type ThemeStore here.
@EnvironmentObject var store: ThemeStore
var body: some View {
List {
ForEach(store.themes) { theme in
Text(theme)
// More logic ...
}
}
}
}
@Environment
用于不同的目的,可以阅读更多信息here.