Reputation: 11
I'm working with CoreData
and SwiftUI
.
CoreData
has an entity called Task
with the name of this task.
In parent View I sort through all tasks:
Parent view:
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [])
private var tasks: FetchedResults<Task>
....
ForEach (tasks) {task in
if !task.isFinished {
HStack {
Text(task.name ?? "Untitled")
Spacer()
Text(String(task.countPomidorsActual))
Button(">", action: {
if timerManager.timerMode == .initial {
tabSelection = "TimerView"
workingTask.workingTask.task = task
} else {
presentWorkingTimerAlert.toggle()
}
})
.frame(width: 30, height: 30)
.buttonStyle(BorderlessButtonStyle())
}
}
}
.....
If the user picks one of these Tasks I give this task to a new class:
struct TaskInWork {
var task: Task
}
class WorkingTask: ObservableObject {
@Published var workingTask = TaskInWork(task: Task())
}
In child view I need to take the name of this passed Task, so:
@Binding var task: Task
....
Text(task.name ?? "Name is empty")
But there is a problem with Preview:
struct TimerView_Previews: PreviewProvider {
static var previews: some View {
let context = PersistenceContainer.shared.container.viewContext
let newTask = Task(context: context)
newTask.name = "Name for test preview"
TimerView(task: .constant(newTask))
.environment(\.managedObjectContext, context)
}
}
It causes error
Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
How can I make a preview with "name for test preview"?
Upvotes: 1
Views: 1313
Reputation: 18914
Use the return keyword to return your timer view. Because of static var previews required view return type and you have added some logical part inside the var. So you need to write explicitly return keywords.
struct TimerView_Previews: PreviewProvider {
static var previews: some View {
let context = PersistenceContainer.shared.container.viewContext
let newTask = Task(context: context)
newTask.name = "Name for test preview"
return TimerView(task: .constant(newTask))
.environment(\.managedObjectContext, context) //<--Here
}
}
Upvotes: 3