[Swift通天遁地]一、超級工具-(16)使用JTAppleCalendar製作美觀的日曆
阿新 • • 發佈:2018-12-25
本文將演示使用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 }