iOS18适配指南之UICalendarView

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
    }
}

效果

切换某周日期

切换某周日期.gif切换某周日期.gif

选择某周日期

选择某周日期.gif选择某周日期.gif

0 人点赞