介绍
- UICalendarView 是 iOS 16 中新增的视图,用于显示日历并支持同时选择日历中的一个或多个日期。
- 只能显示年月日,无法显示时分秒,如果需要时分秒建议继续使用 UIDatePicker。
案例
import UIKit
class ViewController: UIViewController {
lazy var calendarView: UICalendarView = {
let calendarView = UICalendarView(frame: UIScreen.main.bounds)
calendarView.backgroundColor = .white
calendarView.tintColor = .orange
calendarView.calendar = Calendar(identifier: .chinese)
calendarView.locale = Locale(identifier: "zh_Hans_CN")
calendarView.fontDesign = .rounded
calendarView.delegate = self
let multiDateSelection = UICalendarSelectionMultiDate(delegate: self)
calendarView.selectionBehavior = multiDateSelection
return calendarView
}()
var selectedDates: Set<DateComponents> = [] {
didSet {
let formatDate = selectedDates.compactMap { components in
Calendar.current
.date(from: components)?
.formatted(.dateTime.year().month().day()
.locale(Locale(identifier: "zh_Hans_CN")))
}
.formatted()
print(formatDate)
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(calendarView)
}
}
extension ViewController: UICalendarSelectionMultiDateDelegate {
func multiDateSelection(_ selection: UICalendarSelectionMultiDate, didSelectDate dateComponents: DateComponents) {
selectedDates.insert(dateComponents)
}
func multiDateSelection(_ selection: UICalendarSelectionMultiDate, didDeselectDate dateComponents: DateComponents) {
selectedDates.remove(dateComponents)
}
func multiDateSelection(_ selection: UICalendarSelectionMultiDate,
canSelectDate dateComponents: DateComponents) -> Bool {
guard let day = dateComponents.day else {
return false
}
return day.isMultiple(of: 2)
}
func multiDateSelection(_ selection: UICalendarSelectionMultiDate,
canDeselectDate dateComponents: DateComponents) -> Bool {
return true
}
}
extension ViewController: UICalendarViewDelegate {
func calendarView(_ calendarView: UICalendarView, decorationFor dateComponents: DateComponents)
-> UICalendarView.Decoration? {
guard let day = dateComponents.day else {
return nil
}
if !day.isMultiple(of: 2) {
return UICalendarView.Decoration.default(color: .systemGreen, size: .large)
}
return nil
}
}