I’m new in SwiftUI. I’m making an attempt to implementing MultiDatePicker the place consumer can choose minimal knowledge and most date in calendar. As soon as a dates are chosen, all of the dates that are is available in chosen date vary must be robotically chosen.
Right here is my code.
import SwiftUI
struct rely: View {
@Atmosphere(.calendar) var calendar
@State non-public var dates: Set = []
let datePickerComponents: Set = [.calendar, .era, .year, .month, .day]
var datesBinding: Binding> {
Binding {
dates
} set: { newValue in
if newValue.isEmpty {
dates = newValue
} else if newValue.rely > dates.rely {
if newValue.rely == 1 {
dates = newValue
} else if newValue.rely == 2 {
dates = filledRange(selectedDates: newValue)
} else if let firstMissingDate = newValue.subtracting(dates).first {
dates = [firstMissingDate]
} else {
dates = []
}
} else if let firstMissingDate = dates.subtracting(newValue).first {
dates = [firstMissingDate]
} else {
dates = []
}
}
}
var physique: some View {
VStack(spacing: 50){
MultiDatePicker("Choose dates", choice: datesBinding)
.body(peak: 300)
}
.padding()
}
non-public func filledRange(selectedDates: Set) -> Set {
let allDates = selectedDates.compactMap { calendar.date(from: $0) }
let sortedDates = allDates.sorted()
var datesToAdd = [DateComponents]()
if let first = sortedDates.first, let final = sortedDates.final {
var date = first
whereas date < final {
if let nextDate = calendar.date(byAdding: .day, worth: 1, to: date) {
if !sortedDates.incorporates(nextDate) {
let dateComponents = calendar.dateComponents(datePickerComponents, from: nextDate)
datesToAdd.append(dateComponents)
}
date = nextDate
} else {
break
}
}
}
return selectedDates.union(datesToAdd)
}
}
#Preview {
rely()
}
My drawback : It’s working like a allure when consumer choose the vary inside the 4 months but when consumer choose the utmost date after the 4th month then it won’t work.
i.e. if consumer choose from 1st January to tenth January it’s working, it’s working even consumer choose from 1st January to any date until April. As soon as consumer choose the so far that past the Might and so then it isn’t working.
Attaching GIF file right here for higher understanding.
- Gif when consumer choose small date vary interval like January to February then it’s working as anticipated.
- Gif file when consumer choose the dates greater than 4 months like January to Augest September and so forth.