[Swift通天遁地]一、超级工具-(16)使用JTAppleCalendar制作美观的日历
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10173424.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
本文将演示使用JTAppleCalendar制作美观的日历。
首先确保在项目中已经安装了所需的第三方库。
点击【Podfile】,查看安装配置文件。
1 platform :ios, '12.0' 2 use_frameworks! 3 4 target 'DemoApp' do 5 source 'https://github.com/CocoaPods/Specs.git' 6 pod 'JTAppleCalendar', '~> 6.0' 7 end
根据配置文件中的相关配置,安装第三方库
然后点击打开【DemoApp.xcworkspace】项目文件。
在项目文件夹【DemoApp】上鼠标右键,弹出右键菜单:
【New File】->【Cocoa Touch Class】->【Next】->
【Class】:CellView ,类名。
【Subclass of】:JTAppleCalendar ,父类
【Language】:Swift
->【Next】->【Create】
在项目导航区,打开刚刚创建的代码文件【CellView.swift】
1 //引入第三方类库 2 import JTAppleCalendar 3 4 class CellView: JTAppleDayCellView { 5 6 @IBOutlet var dayLabel: UILabel! 7 8 @IBOutlet var selectedView: UIView! 9 }
在项目文件夹【DemoApp】上鼠标右键,弹出右键菜单:
【New File】->【View】视图->【Next】->【Save As】:CellView ->【Create】
点击【CellView.xib】,设置相关属性
1 <?xml version="1.0" encoding="UTF-8"?> 2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="11201" systemVersion="16B2657" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES"> 3 <dependencies> 4 <deployment identifier="iOS"/> 5 <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11161"/> 6 <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> 7 </dependencies> 8 <objects> 9 <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/> 10 <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> 11 <view contentMode="scaleToFill" id="iN0-l3-epB" customClass="CellView" customModule="DemoApp" customModuleProvider="target"> 12 <rect key="frame" x="0.0" y="0.0" width="160" height="160"/> 13 <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> 14 <subviews> 15 <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="WDR-tm-CCJ"> 16 <color key="backgroundColor" red="0.80000000000000004" green="0.59999999999999998" blue="0.0" alpha="1" colorSpace="calibratedRGB"/> 17 <constraints> 18 <constraint firstAttribute="width" constant="40" id="6XG-r3-HC7"/> 19 <constraint firstAttribute="height" constant="40" id="JOI-ha-pr3"/> 20 </constraints> 21 </view> 22 <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qQL-PP-1hg"> 23 <fontDescription key="fontDescription" type="system" pointSize="14"/> 24 <color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/> 25 <nil key="highlightedColor"/> 26 </label> 27 </subviews> 28 <color key="backgroundColor" red="0.2274509804" green="0.15686274510000001" blue="0.29803921570000003" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> 29 <constraints> 30 <constraint firstItem="qQL-PP-1hg" firstAttribute="centerX" secondItem="iN0-l3-epB" secondAttribute="centerX" id="1dS-Ke-SwV"/> 31 <constraint firstItem="qQL-PP-1hg" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="centerY" id="8zP-vN-Rfy"/> 32 <constraint firstItem="WDR-tm-CCJ" firstAttribute="centerX" secondItem="iN0-l3-epB" secondAttribute="centerX" id="aIf-16-vU3"/> 33 <constraint firstItem="WDR-tm-CCJ" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="centerY" id="mhp-tS-eFs"/> 34 </constraints> 35 <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/> 36 <connections> 37 <outlet property="dayLabel" destination="qQL-PP-1hg" id="EzH-lh-Czg"/> 38 <outlet property="selectedView" destination="WDR-tm-CCJ" id="RxZ-fx-mpA"/> 39 </connections> 40 <point key="canvasLocation" x="-87" y="-205"/> 41 </view> 42 </objects> 43 </document>
在项目导航区,打开视图控制器的代码文件【ViewController.swift】
1 import UIKit 2 //在当前的类文件中,引入已经安装的第三方类库 3 import JTAppleCalendar 4 5 //添加需要使用到的相关协议 6 class ViewController: UIViewController, JTAppleCalendarViewDataSource, JTAppleCalendarViewDelegate { 7 8 @IBOutlet var calendarView: JTAppleCalendarView! 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 // Do any additional setup after loading the view, typically from a nib. 12 13 //设置数据源为当前的视图控制器对象 14 calendarView.dataSource = self 15 //设置代理对象为当前的视图控制器对象 16 calendarView.delegate = self 17 //要使用自定义的日历视图,需要注册日历中的日期数字单元格的故事版文件 18 calendarView.registerCellViewXib(file: "CellView") 19 //设置日期数字单元格的间距 20 calendarView.cellInset = CGPoint(x: 0, y: 0) 21 22 //在日历中允许选择多个日期 23 calendarView.allowsMultipleSelection = true 24 //允许进行日期区域的选择 25 calendarView.rangeSelectionWillBeUsed = true 26 27 //将日历视图添加到当前视图控制器的根视图 28 self.view.addSubview(calendarView) 29 } 30 31 //添加一个代理方法,用来监听日历中的数据单元格即将显示的事件 32 func calendar(_ calendar: JTAppleCalendarView, willDisplayCell cell: JTAppleDayCellView, date: Date, cellState: CellState) 33 { 34 //获得即将显示的单元格对象,并转换成自定义的单元格类 35 let myCustomCell = cell as! CellView 36 //设置单元格中的标签的文字内容 37 myCustomCell.dayLabel.text = cellState.text 38 39 //当日历显示的日期为当前月份时 40 if cellState.dateBelongsTo == .thisMonth 41 { 42 //设置数字标签的字体颜色为浅灰色 43 myCustomCell.dayLabel.textColor = UIColor(red: 236/255, 44 green: 234/255, 45 blue: 237/255, 46 alpha: 1.0) 47 } 48 else 49 { 50 //不是当前的月份时,设置另外一种颜色 51 myCustomCell.dayLabel.textColor = UIColor(red: 87/255, 52 green: 72/255, 53 blue: 101/255, 54 alpha: 1.0) 55 } 56 57 //处理日期单元格被选择的事件 58 handleCellSelection(view: cell, cellState: cellState) 59 } 60 61 //添加一个方法,用来响应日期数字单元格被选择的事件 62 func handleCellSelection(view: JTAppleDayCellView?, cellState: CellState) 63 { 64 //获得被选择的日期数字单元格 65 guard let myCustomCell = view as? CellView else 66 { 67 return 68 } 69 //当单元格被选择时 70 if cellState.isSelected 71 { 72 //设置单元格的选择标识视图的圆角半径为20 73 myCustomCell.selectedView.layer.cornerRadius = 20 74 //并设置视图的显示状态为真 75 myCustomCell.selectedView.isHidden = false 76 } 77 else 78 { 79 //当单元格不处选择状态时,隐藏该单元格的标识视图 80 myCustomCell.selectedView.isHidden = true 81 } 82 //同时在控制台输出单元格的日期 83 print("Date:\(cellState.date)") 84 } 85 86 //添加一个代理方法,用来配置日历的相关参数 87 func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters 88 { 89 //初始化一个日期格式对象 90 let formatter = DateFormatter() 91 //设置日期的格式 92 formatter.dateFormat = "yyyy MM dd" 93 94 //初始化两个日期对象 95 //分别标识日历的起始日期 96 let startDate = formatter.date(from: "2018 12 26")! 97 //分别标识日历的结束日期 98 let endDate = Date() 99 100 //初始化一个配置参数对象 101 let parameters = ConfigurationParameters(startDate: startDate,//起始日期 102 endDate: endDate,//结束日期 103 numberOfRows: 6,//日历行数 104 calendar: Calendar.current,//日历类别 105 generateInDates: .forAllMonths,//过去日期 106 generateOutDates: .tillEndOfGrid,//将来日期 107 firstDayOfWeek: .sunday)//每周第一天 108 //返回的日历配置参数对象 109 return parameters 110 } 111 112 //添加一个代理方法,用来监听某个日期被选择时的事件 113 func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleDayCellView?, cellState: CellState) 114 { 115 handleCellSelection(view: cell, cellState: cellState) 116 } 117 118 //添加一个代理方法,用来监听某个日期取消选择时的事件 119 func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleDayCellView?, cellState: CellState) 120 { 121 handleCellSelection(view: cell, cellState: cellState) 122 } 123 124 override func didReceiveMemoryWarning() { 125 super.didReceiveMemoryWarning() 126 // Dispose of any resources that can be recreated. 127 } 128 }