I need help optimizing and fixing my date list builder. Basically the user should be able to build a list of dates in a sheet and it be shown on the original view and go back to that page to add more. Dates should not be repeated hence why I use a set.
Issue: But when the user adds the first date it doesn't show until a second date is added. After some troubleshooting with print I've found that the problem isn't adding the first item to the list, but the ForEach not working until there is a second item.
I've included code for a visual representation of my goal. If you have any questions please leave a comment. Any help would be greatly appreciated. Thanks!
import SwiftUI
struct ContentView: View {
@State private var dates = Set<Date>()
@State private var isDatesShowing = false
var body: some View {
NavigationView{
Form{
Section(""){
addDatesButton
Section{
ForEach(dates.sorted(by: <),id: \.self){ date in
Text(date, style: .date)
.bold()
.foregroundColor(.white)
}
}
}
}
.navigationBarTitle("List of Dates")
.sheet(isPresented: $isDatesShowing){
AddToDateView(dates: $dates)
}
}
.preferredColorScheme(.dark)
}
var addDatesButton: some View{
Button(action: {
isDatesShowing.toggle()
}){
Text("Select Dates")
.bold()
}
}
}
struct AddToDateView: View {
@Environment(\.dismiss) var dismiss
@Binding var dates: Set<Date>
@State var date = Date()
var body: some View {
NavigationView{
Form{
DatePicker(selection: $date, in: Date.now..., displayedComponents: .date) {
Text("Select a date")
}
.datePickerStyle(WheelDatePickerStyle())
Button(action:{
dates.insert(date)
}){
Text("Add Date")
}
Section("Dates"){
ForEach(dates.sorted(by: <),id: \.self){ date in
Button(action: {
dates.remove(date)
}){
Text(date, style: .date)
.bold()
.foregroundColor(.white)
}
}
}
}
.cornerRadius(10)
.navigationBarItems(trailing: submitButton)
}
}
var submitButton: some View{
Button(action: {
dismiss()
}){
Text("Submit")
.bold()
}
}
}