I am new to the calendar. I have an array of dates which is non-consecutive. I want to select and highlight it initially. And, the unhighlighted has to be non-clickable, i.e. the user is only able to click on those dates that are in the array of dates list.
After exploring that I found a way that we can only disable for picking date through start, end and date range only.
I made a view model as
class DateSelectionVM: ObservableObject{
@Published var activeDate = [
DateComponents(year: 2024, month: 3, day: 12),
DateComponents(year: 2024, month: 3, day: 15),
DateComponents(year: 2024, month: 3, day: 18),
DateComponents(year: 2024, month: 3, day: 20),
DateComponents(year: 2024, month: 3, day: 21),
DateComponents(year: 2024, month: 3, day: 27)
]
@Published var selectedDates: Set<DateComponents> = []
var bounds: Range<Date> {
let calendar = Calendar.current
var dates: [Date] = []
for component in activeDate{
dates.append(calendar.date(from: component)!)
}
if let range = dates.dateRange {
print("Date range: \(range.lowerBound) to \(range.upperBound)")
return range
} else {
print("Array is empty")
}
return dates.first!..<dates.last!
}
init() {
calulateDate()
}
private func calulateDate(){
for date in activeDate{
selectedDates.insert(date)
}
}
}
where I defined a activeDate which has to be displayed on the Calender as selected and clickable.
I define my view as
struct DateSelectionView: View {
@ObservedObject var dateSelectionVM = DateSelectionVM()
@Environment(\.calendar) var calendar
var body: some View {
VStack {
Spacer()
VStack{
VStack(alignment: .leading){
HStack{
Text("Your Daily Streak")
.foregroundColor(.blue)
.font(.title2)
Spacer()
Image(systemName: "flame")
.foregroundColor(.blue)
Text("120")
.font(.title)
.bold()
}
Divider()
.padding(EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 0))
Text("Engage daily")
.font(.system(size: 13))
.padding(EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 0))
MultiDatePicker("Select Dates", selection: $dateSelectionVM.selectedDates, in: dateSelectionVM.bounds)
.frame(height: 300)
}
.padding()
}
.background(.gray.opacity(0.2))
.cornerRadius(10)
Spacer()
}
.padding()
.background(.purple.opacity(0.2))
.navigationTitle("Stack")
}
}
The problem I faced was that I wasn't able to disable other dates than activeDate. I know I gave a range of dates that is consecutive so, it permitted the user to click. Is there another way to fix this problem?
I have attached the image. But what I want is that I want to disable 13,14,16,17,19,22,23,24,25,26 as well. Can anyone help me to fix it?
