Swiftui Previews - Unexpected Data

SwiftUI Previews - unexpected data

Why Preview of my ItemView.swift view shows a mixture of example data I have provided + Core Data models created in Live Preview?

  1. the below line initiates context to your persistent data, so makes available all stored core data object to be fetched

     let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  2. the below line creates a new object in the context created above, so it is in context (though to stored) and available for fetching alongside of others stored.

     let testItem = Item.init(context: context)

Thus fetching object from this context ...

    return ItemView(filter: false)
.environment(\.managedObjectContext, context)

... makes all - stored and created - available in Preview.

SwiftUI - too many previews

Replace

var body: some View {
// I think problem is here
ForEach(items, id: \.self) {item in
Text("\(item.date ?? Date())")
}
}

with

var body: some View {

/// add VStack here!
VStack {
ForEach(items, id: \.self) {item in
Text("\(item.date ?? Date())")
}
}
}

Without a VStack or some other container, your body consists of multiple views. This makes Xcode generate a preview for each of them... see here for a similar question.

How to fix multiple SwiftUI previews

You'll need to put both Texts in a VStack or similar.

struct ContentView: View {
var body: some View {
VStack {
Text("Example title")
Text("Example title 2")
}
}
}

It seems that Xcode automatically adds a new preview for each separate view returned in the body var (It used to throw an error, but I think Xcode 12 changed some things).

Error when using Canvas to preview SwiftUI view

Clean Build Folder, then kill Xcode, start Xcode, do a full Build may (sometimes) fix the problems. Then the whole circus starst again.
I think it is a bit of a shame on Apple. Most frustrating of all (for me at least) is that documentation is virtually non existing. It is all trial and error. Mostly error.



Related Topics



Leave a reply



Submit