Ralf Ebert
Ralf Ebert

Reputation: 4082

Monthly calender sheet in SwiftUI

How can you show a monthly calendar sheet (similiar to the one in the Calendar app) to select a single date in SwiftUI?

Something like this:

Upvotes: 1

Views: 919

Answers (1)

Ralf Ebert
Ralf Ebert

Reputation: 4082

Including the CVCalendar component via the Swift Package manager and wrapping it as UIViewRepresentable does the trick:

For example:

import CVCalendar
import SwiftUI
import UIKit

/// CalendarView is a SwiftUI wrapper for the [CVCalendar](https://github.com/CVCalendar/CVCalendar) component
struct CalendarView: UIViewRepresentable {

    @Binding var date: Date

    func makeUIView(context: Context) -> CVCalendarView {
        let view = CVCalendarView(frame: CGRect(x: 0, y: 0, width: 350, height: 350))
        view.calendarDelegate = context.coordinator
        view.commitCalendarViewUpdate()
        view.setContentHuggingPriority(.required, for: .horizontal)
        return view
    }

    func updateUIView(_ uiView: CVCalendarView, context: Context) {
        uiView.toggleViewWithDate(self.date)
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(date: self.$date)
    }

    class Coordinator: NSObject, CVCalendarViewDelegate {

        @Binding var date: Date

        init(date: Binding<Date>) {
            self._date = date
        }

        func presentationMode() -> CalendarMode {
            .monthView
        }

        func firstWeekday() -> Weekday {
            Weekday(rawValue: Calendar.current.firstWeekday)!
        }

        func presentedDateUpdated(_ date: CVDate) {
            if let date = date.convertedDate() {
                self.date = date
            }
        }

    }

}

struct CalendarView_Previews: PreviewProvider {

    @State static var date = Date()

    static var previews: some View {
        CalendarView(date: $date)
    }
}

Upvotes: 1

Related Questions