How do I limit items to display in a List using ‘filter’? This brief tutorial reflects the solution to this simple problem that I encountered during my SwiftUI learning journey:
Szenario used here: From messages created, show only current ones (i.e. from today).
Create the “Message” model as an observable object:
Create the class “MockData” as ObservableObject, and pass in some data using 3 different dates:
Create the view file “CellView” showing the message text and a time stamp:
Initial List view
An initial list would use the mock data and pass in the array of all message items therein:
This with the following result:
The ListView struct limits the implementation of filter, one of which would be a function returning the filtered array. Hence, we can use such function to pass the filtered items instead of all items from the mock data. Here, this is achieved using a Swift closure and ‘isDateInToday’.
I hope you enjoyed reading this brief tutorial. We made good use of ‘filter’ to limit the items to show in a SwiftUI List.
You can find the Github link here: https://github.com/fugu2/List-Filter.