Search code examples
swiftuidatepicker

SwiftUI MultiDatePicker selection breaks on non-empty initial selection


I need an initial selection for MultiDatePicker. I tried assigning it in init as you can see below and in onAppear. In both cases deselecting the initial selection does not work, it always stays in dates. How to fix this?

import SwiftUI

struct ContentView: View {
    @State private var dates: Set<DateComponents>
    
    init() {
        let now = Calendar.current.dateComponents([.year, .month, .day], from: .now)
        _dates = State(initialValue: [now])
    }
    
    var body: some View {
        VStack {
            MultiDatePicker("", selection: $dates)
                .onChange(of: dates) {_ in
                    print("Selection changed")
                }
            Text(datesStr)
        }.padding()
    }
    
    var datesStr: String {
        dates
            .map{ Calendar.current.date(from: $0)!.formatted(date: .numeric, time: .omitted) }
            .joined(separator: "\n")
    }
}

Same problem with this one-liner by the way (which does not meet my needs because it is not dynamic):

@State private var dates: Set<DateComponents> = [Calendar.current.dateComponents([.year, .month, .day], from: .now)]

Tested in Xcode 14.0.1 and 14.1 beta 3.


Solution

  • Simply use [.calendar, .era, .year, .month, .day] instead of [.year, .month, .day]. That is the DateComponents format MultiDatePicker expects.

    I just found this solution after wondering why the same DateComponents can appear twice in the Set (which as you know only allows unique elements). Well, they were not exactly the same.