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?
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
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 Text
s 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
How to Reconnect Akplayer and Akmixer After Audiokit.Stop()
How to Pause an Animation in Swiftui
Crashlytics Doesn't Work with Xcode 10 Beta
Create Record Only If Parent Exists in Vapor Using Fluent
Swift Compile Error, Subclassing Nsvalue, Using Super.Init(Nonretainedobject:)
On Demand Resources "0 Asset Packs"
Reactive Cocoa/Reactive Swift - Swift 3.0 Missing Methods
Swift 1.2 Assigning Let After Initialization
Why Is My App Returning Hundreds of Errors That Say "Undefinedsymbol"
Index or Range of Second Ocurence of Bytes in File
Arkit/Scenekit on iOS 14 Throws New Warning (Metal)
How to Grab The Parent Object from a Subview
Reduce Float Precision Using Regexp in Swift
Mapview Shows White Overlay on Interaction
Actions Assigned to Nsmenuitem Dont Seem to Work
Swift Preserve UIswitch State on UIlongpress
Swift Struct Adopting Protocol with Static Read-Write Property Doesn't Conform