2024-09-09 11:34:08
浏览数 (1)
介绍
- 增加类型
UICalendarSelectionWeekOfYear
,表示可以从日历视图中选择一年中的某周日期。 selectionBehavior
属性增加了支持UICalendarSelectionWeekOfYear
的选项,可以按周选择日期。
案例
代码语言:swift
复制import UIKit
class ViewController: UIViewController {
lazy var calendarSelectionWeekOfYear = UICalendarSelectionWeekOfYear(delegate: self)
lazy var calendarView: UICalendarView = {
let calendarView = UICalendarView(frame: UIScreen.main.bounds)
calendarView.locale = Locale(identifier: "zh_Hans_CN")
// iOS18新增,一次选择一周日期
calendarView.selectionBehavior = calendarSelectionWeekOfYear
// 选中一年内的某周日期
calendarSelectionWeekOfYear.selectedWeekOfYear = DateComponents(weekOfYear: 36, yearForWeekOfYear: 2024)
return calendarView
}()
// 用户选择的某周日期的第一天
var selectedDate: DateComponents = DateComponents(weekOfYear: 36, yearForWeekOfYear: 2024) {
didSet {
let startDateOfSelecedWeek = Calendar.current
.date(from: selectedDate)?
.formatted(.dateTime.year().month().day()
.locale(Locale(identifier: "zh_Hans_CN")))
print(startDateOfSelecedWeek ?? Date.now)
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(calendarView)
DispatchQueue.main.asyncAfter(deadline: .now() 3) {
self.calendarSelectionWeekOfYear.setSelected(DateComponents(weekOfYear: 38, yearForWeekOfYear: 2024), animated: true)
}
}
}
// MARK: - UICalendarSelectionWeekOfYearDelegate
extension ViewController: UICalendarSelectionWeekOfYearDelegate {
// MARK: 选择某周日期
func week(ofYearSelection selection: UICalendarSelectionWeekOfYear, didSelectWeekOfYear weekOfYearComponents: DateComponents?) {
guard let weekOfYearComponents = weekOfYearComponents else { return }
selectedDate = weekOfYearComponents
}
// MARK: 是否能够选择某周日期
func week(ofYearSelection selection: UICalendarSelectionWeekOfYear, canSelectWeekOfYear weekOfYearComponents: DateComponents?) -> Bool {
return true
}
}
效果
切换某周日期
选择某周日期