It’s available from iOS16.
UIKit
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configureCalenderView()
}
private func configureCalenderView() {
view.backgroundColor = .white
let selection = UICalendarSelectionSingleDate(delegate: self)
let calendarView = UICalendarView()
calendarView.frame = view.bounds
calendarView.delegate = self
calendarView.selectionBehavior = selection
view.addSubview(calendarView)
}
}
extension HomeViewController: UICalendarViewDelegate {}
extension HomeViewController: UICalendarSelectionSingleDateDelegate {
func dateSelection(_ selection: UICalendarSelectionSingleDate, didSelectDate dateComponents: DateComponents?) {
guard let dateComponents = dateComponents,
let year = dateComponents.year,
let month = dateComponents.month,
let day = dateComponents.day else {
return
}
print("Year: \(year), Month: \(month), Day: \(day)")
}
}
SwiftUI
import SwiftUI
struct CalendarView: UIViewRepresentable {
let didSelectDate: (_ dateComponents: DateComponents) -> Void
final public class Coordinator: NSObject, UICalendarSelectionSingleDateDelegate {
let didSelectDate: (_ dateComponents: DateComponents) -> Void
init(
didSelectDate: @escaping (_ dateComponents: DateComponents) -> Void
) {
self.didSelectDate = didSelectDate
}
public func dateSelection(_ selection: UICalendarSelectionSingleDate, didSelectDate dateComponents: DateComponents?) {
guard let dateComponents = dateComponents else {
return
}
didSelectDate(dateComponents)
}
}
public func makeCoordinator() -> Coordinator {
Coordinator(didSelectDate: didSelectDate)
}
func makeUIView(context: Context) -> some UIView {
let selection = UICalendarSelectionSingleDate(delegate: context.coordinator)
let calendarView = UICalendarView()
calendarView.selectionBehavior = selection
return calendarView
}
func updateUIView(_ uiView: UIViewType, context: Context) {}
}
struct CalendarView_Previews: PreviewProvider {
static var previews: some View {
CalendarView { dateComponents in
}
}
}
import SwiftUI
struct HomeView: View {
var body: some View {
CalendarView { dateComponents in
guard let year = dateComponents.year,
let month = dateComponents.month,
let day = dateComponents.day else {
return
}
print("Year: \(year), Month: \(month), Day: \(day)")
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}