I searched a lot about this error but it seems there's no solution...
UITableView was told to layout its visible cells and other contents without being in the
view hierarchy (the table view or one of its superviews has not been added to a window).
This may cause bugs by forcing views inside the table view to load and perform layout without
accurate information (e.g. table view bounds, trait collection, layout margins, safe area
insets, etc), and will also cause unnecessary performance overhead due to extra layout passes.
Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in
the debugger and see what caused this to occur, so you can avoid this action altogether if
possible, or defer it until the table view has been added to a window
This is my actual code:
struct ContentView: View {
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(fetchRequest: FavoriteBooks.getAllFavoriteBooks()) var favoriteBooks:FetchedResults<FavoriteBooks>
#ObservedObject var bookData = BookDataLoader()
var body: some View {
NavigationView {
List {
Section {
NavigationLink(destination: FavoriteView()) {
Text("Go to favorites")
}
}
Section {
ForEach(0 ..< bookData.booksData.count) { num in
HStack {
Text("\(self.bookData.booksData[num].titolo)")
Button(action: {
**let favoriteBooks = FavoriteBooks(context: self.managedObjectContext)
favoriteBooks.titolo = self.bookData.booksData[num].titolo**
}) {
Image(systemName: "heart")
}
}
}
}
}
}
}
}
struct FavoriteView: View {
#Environment(\.managedObjectContext) var managedObjectContext
#FetchRequest(fetchRequest: FavoriteBooks.getAllFavoriteBooks()) var favoriteBooks:FetchedResults<FavoriteBooks>
var body: some View {
List {
**ForEach (self.favoriteBooks) { book in
Text("\(book.titolo!))")**
}
}
}
}
I just selected on bold what makes this error and I don't know how to avoid it because if I launch the app it doesn't crash but I cannot do anything.
Thanks in advance
You have a couple issues here. The first is, when you use ForEach, if your content is supposed to be able to change (which, with FetchRequest it is...) then either FavoriteBooks needs to be Identifiable or you need to pass in your id. You actually do this twice in the code:
ForEach(0 ..< bookData.booksData.count) { num in
// SwiftUI thinks this content never changes because it doesn't know how to resolve those changes. you didn't tell it
}
should be:
ForEach(0 ..< bookData.booksData.count, id: \.self) { ... }
Notice now you are telling it what the id is. If the count of bookData.booksData changes, now SwiftUI can resolve those changes. But really, why do you need the index in this case specifically? Why not just:
ForEach(bookData.booksData) { book in ... }
If you make this object type conform to Identifiable, you now have the book already.
Now on to another problem, your button action. Why are you re-executing the CoreData query here? You have the Set of the objects you want. This is another reason to just use ForEach(bookData.booksData), you don't have to resolve the index here. But in general, you should never need to re-execute your core data query to find a specific object. what this actually does is then trigger another update on your entire view hierarchy, which is likely why you get the error you're getting. you aren't supposed to be doing this.
Related
TL;DR: If I have a view containing a NavigationSplitView(sidebar:detail:), with a property (such as a State or StateObject) tracking user selection, how should I make it so that the sidebar and detail views observe the user selection, but the parent view does not?
Using SwiftUI's new NavigationSplitView (or the deprecated NavigationView), a common paradigm is to have a list of selectable items in the sidebar view, with details of the selected item in the detail view. The selection, of course, needs to be observed, usually from within an ObservedObject.
struct ExampleView: View {
#StateObject private var viewModel = ExampleViewModel()
var body: some View {
NavigationSplitView {
SidebarView(selection: $viewModel.selection)
} detail: {
DetailView(item: viewModel.selection)
}
}
}
struct SidebarView: View {
let selectableItems: [Item] = []
#Binding var selection: Item?
var body: some View {
List(selectableItems, selection: $viewModel.selected) { item in
NavigationLink(value: item) { Text(item.name) }
}
}
}
struct DetailView: View {
let item: Item?
var body: some View {
// Details of the selected item
}
}
#MainActor
final class ExampleViewModel: ObservableObject {
#Published var selection: Item? = nil
}
This, however, poses a problem: the ExampleView owns the ExampleViewModel used for tracking the selection, which means that it gets recalculated whenever the selection changes. This, in turn, causes its children SidebarView and DetailView to be redrawn.
Since we want those children to be recalculated, one might be forgiven for thinking that everything is as intended. However, the ExampleView itself should not be recalculated in my opinion, because doing so will not only update the child views (intended), but also everything in the parent view (not intended). This is especially true if its body is composed of other views, modifiers, or setup work. Case in point: in this example, the NavigationSplitView itself will also be recalculated, which I don't think is what we want.
Almost all tutorials, guides and examples I see online use a version of the above example - sometimes the viewModel is passed as an ObservedObject, or as an EnvironmentObject, but they all share the same trait in that the parent view containing the NavigationSplitView is observing the property that should only be observed by the children of NavigationSplitView.
My current solution is to initiate the viewmodel in the parent view, but not observe it:
struct ExampleView: View {
let viewModel = ExampleViewModel()
...
}
#MainActor
final class ExampleViewModel: ObservableObject {
#Published var selection: Item? = nil
nonisolated init() { }
}
This way, the parent view will remain intact (at least in regards to user selection); however, this will cause the ExampleViewModel to be recreated if anything else would cause the ExampleView to be redrawn - effectively resetting our user selection. Additionally, we are unable to pass any of the viewModel's properties as bindings. So while it works for my current use-case, I don't consider this an effective solution.
The following code is simplified and isolated. It is intended to have a Text() view, which shows the number of times the button has been clicked, and a Button() to increment the text view.
The issue: Clicking the button does not actually change the Text() view, and it continues to display "1"
struct Temp: View {
#State var h = struct1()
var body: some View {
VStack {
Button(action: {
h.num += 1
}, label: {
Text("CLICK ME")
})
Text(String(h.num))
}
}
}
struct struct1 {
#State var num = 1
}
What's funny is that the same code works in swift playgrounds (obviously with the Text() changed to print()). So, I'm wondering if this is an XCode specific bug? If not, why is this happening?
Remove #State from the variable in struct1
SwiftUI wrappers are only for SwiftUI Views with the exception of #Published inside an ObservableObject.
I have not found this in any documentation explicitly but the wrappers conform to DynamicProperty and of you look at the documentation for that it says that
The view gives values to these properties prior to recomputing the view’s body.
So it is implied that if the wrapped variable is not in a struct that is also a SwiftUI View it will not get an updated value because it does not have a body.
https://developer.apple.com/documentation/swiftui/dynamicproperty
The bug is that it works in Playgrounds but Playground seems to have a few of these things. Likely because of the way it complies and runs.
If you create a very simple example that shows a lot of leaking object within the SwiftUI code if you nest NavigationView/List/ForEach and return different types of views in the ForEach closure.
import SwiftUI
class MyStateObject : ObservableObject {
#Published var items:[Int]
init() {
self.items = Array(0..<1000)
}
}
struct ContentView: View {
#StateObject var stateObject = MyStateObject()
var body: some View {
NavigationView {
List {
ForEach(stateObject.items, id: \.self) { item in
if(item % 2 == 0) {
Text("Even \(item)")
}
else {
Image(systemName: "xmark.octagon")
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I strongly suspect this is a bug in SwiftUI but I wanted to ask if I am doing anything wrong here.
You can see the leaks by attaching Instruments. It will show immediately and increase if you scroll through the list.
Interestingly, it seems the leaks don't happen if
you remove the NavigationView from the hierarchy.
you only supply one type of View in ForEach (and don't branch via if/else).
the list of items you want to show is small (100 does not seem to result in leaks).
(Tested on XCode 12.5 and iOS 14.5 Simulator and Device,)
Since in my app I am pretty much reliant on this kind of hierarchy, I am very open for some suggestions on how to avoid the leaking.
By accident i added a modifier to my swift UI view without a leading point. And it compiled. And i can not wrap my head around why i did that.
Here some example Code:
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: DetailView(),
label: {
Text("Goto Detail")
})
navigationTitle("ContentView")
}
}
}
struct DetailView: View {
var body: some View {
Text("Detail View")
.padding()
navigationTitle("Detail")
}
}
Somehow even stranger is that the first "wrong" modifier navigationTitle("ContentView") does just nothing.
The second one navigationTitle("Detail") lets the App crash when navigating to the View during runtime.
Similar to this is
struct DetailView: View {
var body: some View {
padding()
}
}
This View does compile but just crashes, if tried to shown with Previews. And it just can't be navigated to.
I would really expect this code to not even compile.
Is somebody able to explain this?
If you refer to a method by its simple name (e.g. navigationTitle), it's kind of like saying self.navigationTitle:
struct DetailView: View {
var body: some View {
Text("Detail View")
.padding()
self.navigationTitle("Detail")
}
}
This is valid, because self is also a View, and that modifier is available on all Views. It gives you a new view that is self, but with a navigation title of Detail. And you are using both of them as the body. Normally you can't return multiple things from a property, but it works here because the body protocol requirement is marked #ViewBuilder.
Of course, you are using self as the self's body, and you can't have self referencing views, so it fails at runtime.
If you add self. to the other cases, it's pretty easy to understand why they compile:
struct DetailView: View {
var body: some View {
self.padding() // self conforms to View, so you can apply padding()
// padding() returns another View, so it's valid to return here
}
}
"The body of DetailView is itself, but with some padding."
NavigationView {
NavigationLink(
destination: DetailView(),
label: {
Text("Goto Detail")
})
self.navigationTitle("ContentView")
}
"The navigation view consists of a navigation link, and ContentView itself (what self means here) with a navigation title of ContentView"
This doesn't crash immediately either because NavigationView's initialiser is smart enough to ignore the junk ContentView that you have given it, or because there is an extra level of indirect-ness to the self-referencing. I don't think we can know exactly why it crashes/doesn't crash immediately, until SwiftUI becomes open source.
I'm attempting to use SwiftUI and CoreData to build a macOS application. This application's main window has a NavigationView, with list items bound to a fetch request, and selecting any of these items populates the detail view. The navigation view goes kind of like this:
NavigationView {
VStack(spacing: 0) {
List(fetchRequest) { DetailRow(model: $0) }
.listStyle(SidebarListStyle())
HStack {
Button(action: add) { Text("+") }
Button(action: remove) { Text("-") }
}
}
Text("Select a model object")
}.navigationViewStyle(DoubleColumnNavigationViewStyle())
DetailRow is a NavigationLink that also defines the detail view:
NavigationLink(destination: ModelDetail(model: model)) {
Text(model.name)
}
I believe that the contents of ModelDetail isn't very important; either way, I'm fairly flexible with it.
In the navigation view, the "-" button, which calls the remove method, should delete the currently-selected model object and return to the default, empty detail view. Unfortunately, I'm struggling to come up with the right way to do this. I believe that I need the following interactions to happen:
subview communicates to navigation view which model object is currently selected
user clicks "-" button, navigation view's remove method deletes currently selected object
subview notices that its model object is being deleted
→ subview calls PresentationMode.dismiss()
Step 3 is the one I'm struggling with. Everything is working out alright so far without using view-model classes on top of the Core Data classes, but I feel stuck trying to figure out how to get the subview to call dismiss(). This needs to happen from the detail view, because it gets the PresentationMode from the environment, and the NavigationView changes it.
While I can get a Binding to the model's isDeleted property through #ObservedObject, I don't know how I can actually react to that change; Binding appears to use publishers under the hood, but they don't expose a publisher that I could hook up to with onPublish, for instance.
KVO over isDeleted might be possible, but listening from a value type isn't great; there's no good place to remove the observer, which could become problematic were the app to run for too long.
What's the guidance for this type of problem?
Heres my solution.
This is my NoteDetailView. It allows deletion from this view, or the "master" view in the Navigation hierarchy. This solution works on Mac, iPad, and iPhone.
I added an optional dateDeleted to my Entity. When a record is deleted, I simply add a value of Date() to this attribute and save the context. In my FetchRequests, I simply predicate for dateDeleted = nil. I'm going to add a trash can and stuff to my app later so people can view or permanently empty their trash.
Then I use a state variable and a notification to clear my View. You can change the code up for the functionality you want:
struct NoteDetailView: View {
var note: Note
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
#Environment(\.managedObjectContext) var managedObjectContext
#State var noteBody: String = ""
#State var showEditNoteView: Bool = false
#State var showEmptyView: Bool = false
init(note: Note) {
self.note = note
self._noteBody = State(initialValue: note.body)
}
var body: some View {
VStack {
if (!showEmptyView) {
Text("NOT DELETED")
}
else {
EmptyView()
}
}
.navigationBarTitle(!showEmptyView ? note.title : "")
.navigationBarItems(trailing:
HStack {
if (!showEmptyView) {
Button(action: {
self.showEditNoteView.toggle()
}, label: {
NavBarImage(image: "pencil")
})
.sheet(isPresented: $showEditNoteView, content: {
EditNoteView(note: self.note).environment(\.managedObjectContext, self.managedObjectContext)
})
}
}
)
.onReceive(NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)) { _ in
if (self.note.dateDeleted != nil) {
self.showEmptyView = true
self.presentationMode.wrappedValue.dismiss()
}
}
}
}