Does anyone know how I can animate a sorting change to grid items while iterating off of the array index in a ForEach?
I am showing a grid of items (LazyVGrid) from an array and the user can change the sort order of these items. When the sort order changes, I'd like to animate the change in the grid. This would work great if I were to use code similar to the following:
Button {
withAnimation {
noteModel.sortMethod = noteModel.sortMethod.next()
}
} label: {
Text("Change Sort Order")
}
ScrollView {
LazyVGrid(columns: columns) {
ForEach(self.notes, id: \.self) { note in
VStack {
Text(note.title)
Text(note.body)
}
.padding()
}
}
}
However, if my ForEach iterates off of the array index the change does not animate. So it won't animate if my code is similar to this:
Button {
withAnimation {
noteModel.sortMethod = noteModel.sortMethod.next()
}
} label: {
Text("Change Sort Order")
}
ScrollView {
LazyVGrid(columns: columns) {
ForEach(self.notes.indices, id: \.self) { idx in
VStack {
Text(self.notes[idx].title)
Text(self.notes[idx].body)
}
.padding()
}
}
}
Why don't I just do it the first way? The reason is because I found a great resource for dynamically adjusting frame sizes for items inside a grid (found here: https://swiftui-lab.com/impossible-grids/), but that requires the use of array indices in order to work. It's pretty cool and I am hoping I don't have to choose one or the other (dynamic sizing or animate changes).
Thoughts or ideas would be greatly appreciated. Thanks!
ForEach in SwiftUI isn’t the same as a for loop. Your data needs to be identifiable for structural identity to work and you certainly should not be using indices. Either implement the Identifiable protocol or tell ForEach what key path is a unique ID (or is a getter that creates one from other properties) in the item struct. Don’t ever use id:\.self.
You can learn more about structural identity in the video WWDC 2021 Demystify SwiftUI
Related
are lists in SwiftUI really lazy?
I am having a list of 5000 elements fetched from coreData and I want to display them in a list. I read a lot of comments (like that: https://developer.apple.com/forums/thread/651256) that Lists are lazy but for me it looks like they are not.... Loading the list takes 15 seconds.
List(element, id: \.objectID, selection: $selection) { file in
RowView(file)
}
If I use a ScrollView + LazyVStack + ForEach instead the loading takes less than a second.
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(element, id: \.objectID) { file in
RowView(file)
.onTapGesture {
selection = Set([file.objectID])
}
}
}
}
I would prefer taking a list to make use of the functionalities it provides.
Am I doing something wrong or is list not lazy?
Thanks for help!
(i am working with SwiftUI (for Mac)).
I have a ForEach loop inside a TabView. Whenever I try to build the project using the index (for lack of a better word, here: slide) variable in a condition, it stalls and is not building; it's not showing any errors. If I'm using it interpolated, it works/builds.
TabView {
ForEach(1...3, id: \.self) { slide in
HStack {
if slide == 1 {
Text("Do something if slide is 1st slide") // doesn't work
}
Text("Test \(slide)") // works
}
.tag(slide)
}
}
Thanks for any tips!
Edit: Deleted case 2)
Edit: Added Tabview
I have a List in my App. When I click on an Item in the List it opens another List. The First List looks fine, but the second List looks too big. Here is how it looks normal(good):
And here is the List that looks not good:
On the second Picture, the Problems I have are:
the title is too big
the list item starts too far away from the title
Thats the Code, the Code looks the same in both Lists. The only difference is that I used some different variable names in the second one.
return VStack {
ZStack {
NavigationView {
List {
ForEach(zettelArr) { x in
NavigationLink(destination: ZettelViewDetails(passedVar: x)) {
Text("\(x.name)")
}
}
}.navigationBarTitle(alertVariable)
.navigationBarItems(trailing: Button(action: {
alertView()
//self.isShown = true
}) {
Image(systemName: "plus")
})
}
//SwiftUIAlertViewWithTextBox(isShown: $isShown, message: $msg, title: $title)
}
}
My goal is, that the second List looks exactly like the Main List.
How is this possible ?
Okay I don't know why the formatting from the pictures are not working, maybe I am just dumb. The first Picture is the MainList that looks like I want it to look and the second one is the list that is formatted differently, even though its quite the same Code.
You are using NavigationView for both lists view , while only the first one should be inside a NavigationView
Your ZettelViewDetails shouldn't have NavigationView as parent
Example :
Main
NavigationView {
List {
ForEach(zettelArr) { x in
NavigationLink(destination: ZettelViewDetails(passedVar: x))
{
Text("\(x.name)")
}
}
}.navigationBarTitle(alertVariable)
}
Details
VStack {
ForEach(zettelArr) { x in
NavigationLink(destination: ZettelViewDetails(passedVar: x)) {
Text("\(x.name)")
}
}
}
I have a list of reminders grouped into sections by completion and date. With data coming from an ObservedObject DataStore called global. I pass a realmBinding to the cell. The cell can update this binding and it will trigger the data store to update.
List {
// Past Due
if self.global.pastDueReminders.count > 0 {
Section(header: SectionHeader {}){
ForEach(self.global.pastDueReminders) { reminder in
NavigationLink(destination: ReminderDetail( reminder: reminder.realmBinding())) {
GeneralReminderCell(reminder: reminder.realmBinding())
}
}
}
}
// Completed
if self.global.completeReminders.count > 0 {
// Same as PastDue but for Completed
}
}
The cell looks something like:
struct GeneralReminderCell: View {
#Binding var reminder:Reminder
var body: some View {
HStack(alignment:.top, spacing: 10) {
Image(systemName: reminder.completed ? "checkmark.circle.fill" : "circle")
.onTapGesture(perform:{ self.reminder.completed = !self.reminder.completed })
VStack(alignment: .leading, spacing: 2) {
Text("Follow up with \(reminder.client.fullName)").fontWeight(.semibold)
if reminder.title.count > 0 {
Text(reminder.title)
}
Text(reminder.date.formatted()).foregroundColor(.gray)
}
}.padding(.vertical, 10)
}
}
When tapping on an image it toggles the reminder completion state and its position changes in the List view. The image that was tapped should changed to a filled in check when completed.
This behaviour almost always happens as expected, but sometimes the checked image will get out of sync with the completed state of reminder. I've look at this for quite some time and have not made much headway. Why is the checked image not always matching the state of the data?
Even though this is a very old question, I may have been working on what appears to be this same problem. In my case, my App is running on macOS. At first, the problem also seemed to be very intermittent and had been difficult to reproduce consistently.
I also have a View with a ForEach supplying rows to a List. My row's View contains an #State for an Optional Image that gets updated several different ways via actions performed by that same row View (e.g. Continuity Camera, file picker or drag & drop). The issue is that sometimes the new Image is shown and sometimes it is not shown. Using Self._printChanges() I am able to see that the #State is changing and the row's body it is being redrawn, however, the rendered View does not change. The only pattern that I am able to observe is that this issue only seems to occur with the last row in the List. Based on the success of my workaround below, it seems to confirm that there is an issue with the way SwiftUI's List reuses table cells.
My solution/workaround is to replace:
List {
ForEach {
}
}
With:
ScrollView {
LazyVStack {
ForEach {
}
}
}
We can create new text views out of several small ones using +, which is an easy way of creating more advanced formatting. For example, this creates three text views in different colors and combines them together:
struct ContentView: View {
var body: some View {
Text("Colored ")
.foregroundColor(.red)
+
Text("SwifUI ")
.foregroundColor(.green)
+
Text("Text")
.foregroundColor(.blue)
}
}
But how can I create combined text views by looping through. For example (which doesn't work)
View v;
ForEach((1...3), id: \.self) {
v.append(Text("\($0)"))
}
You are essentially trying to get an expression of type Text, from a sequence 0...3. You can first map the sequence to Text objects. How do you combine a sequence of objects to a single one? reduce!
(1...3).map { Text("\($0)") }.reduce(Text(""), +)
Note that Text("") acts like the identity element of the + operation.