Reputation: 1
I'm creating an app with SwiftUI. I have an array of data and a list showing them. The array contains various elements which contain a username and a date for each element. Something like that:
struct History: Identifiable {
let id = UUID()
var userName: String
var date:String
}
var itemsHistory = [
History(userName: "Liam", date: "2020-06-17" ),
History(userName: "Noah", date: "2019-04-14" ),
History(userName: "James", date: "2022-04-13" ),
]
List {
ForEach(itemsHistory) { item in
VStack(alignment: .leading) {
Text(item.userName)
.font(.headline)
Text(item.date)
.foregroundColor(.secondary)
}
}
}
}
My question is:
How can I use one or two datapickers
to only show users in a certain date range? For example: from the datepicker
I select the range between 2020-01-01 and 2020-02-12 and the list must show only the users who have the date that is in that range.
Thank you very much. It is the first time that I am writing here.
Upvotes: 0
Views: 252
Reputation: 285190
First declare date
as Date
, it's easier to compare
struct History: Identifiable {
let id = UUID()
var userName: String
var date: Date
}
Get start and end date from the pickers
@State private var startDate = Date()
@State private var endDate = Date()
DatePicker(
"Start Date",
selection: $startDate,
displayedComponents: [.date]
)
DatePicker(
"End Date",
selection: $endDate,
displayedComponents: [.date]
)
Then filter the items
let filteredItems = endDate < startDate ? [] : itemsHistory.filter { item in
(startDate...endDate).contains(item.date)
}
Upvotes: 1