iOS进阶+实战

iOS16适配指南之UICalendarView

2022-08-08  本文已影响0人  YungFan

介绍

案例

//  Created by YungFan
import UIKit

class ViewController: UIViewController {
    // 创建UICalendarView
    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)
    }
}

// MARK: - UICalendarSelectionMultiDateDelegate
extension ViewController: UICalendarSelectionMultiDateDelegate {
    // MARK: 选择了日期
    func multiDateSelection(_ selection: UICalendarSelectionMultiDate, didSelectDate dateComponents: DateComponents) {
        selectedDates.insert(dateComponents)
    }

    // MARK: 取消选择了日期
    func multiDateSelection(_ selection: UICalendarSelectionMultiDate, didDeselectDate dateComponents: DateComponents) {
        selectedDates.remove(dateComponents)
    }

    // MARK: 是否能够选择日期
    func multiDateSelection(_ selection: UICalendarSelectionMultiDate,
                            canSelectDate dateComponents: DateComponents) -> Bool {
        guard let day = dateComponents.day else {
            return false
        }
        // 只能选择偶数日
        return day.isMultiple(of: 2)
    }

    // MARK: 是否能够取消选择日期
    func multiDateSelection(_ selection: UICalendarSelectionMultiDate,
                            canDeselectDate dateComponents: DateComponents) -> Bool {
        return true
    }
}

// MARK: - UICalendarViewDelegate
extension ViewController: UICalendarViewDelegate {
    // MARK: 装饰视图,显示在日历数字下边区域
    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
    }
}
上一篇下一篇

猜你喜欢

热点阅读