終於剩下統計圖表的部分了!!!
在網路上搜尋後有一個套件是比較多人使用的,因此我們也用他吧!
首先,先在Podfile中加入Charts和ChartsRealm
接著,打開Terminal,輸入pod update指令,更新Cocoapod導入的library們
這樣就可以發現我們xcode專案左側,多了Charts的套件可以用了喔!
設定完Cocoapods後,我們打開Main.storyboard,新增一個View Controller名為Chart,在Month Scene的左上角增加一個Chart的UIButton,onclick開啟Chart View Controller Scene
接著,Focus到Chart View Controller上
然後可以先在ChartViewController.swift中加入切換月份的相關程式碼,以及取消功能
class ChartViewController: UIViewController {
let sqlManager = (UIApplication.shared.delegate as! AppDelegate).sqlManager
@IBOutlet weak var showView: UIView!
@IBOutlet weak var calendarTitle: UILabel!
@IBOutlet weak var chartsType: UISegmentedControl!
let monthTitle = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
var currentYear = Calendar.current.component(.year, from: Date())
var currentMonth = Calendar.current.component(.month, from: Date())
var currentYM: String {
if currentMonth < 10 {
return "\(currentYear)0\(currentMonth)"
} else {
return "\(currentYear)\(currentMonth)"
}
}
var daysCount: Int {
// 設定目前月份
let dateComponents = DateComponents(year: currentYear, month: currentMonth)
let date = Calendar.current.date(from: dateComponents)!
// 取得該月份天數
return Calendar.current.range(of: .day, in: .month, for: date)?.count ?? 0
}
var categoryDict: [Int : String] = [:]
override func viewDidLoad() {
super.viewDidLoad()
if let path = Bundle.main.path(forResource: "Category", ofType: "plist"),
let array = NSArray(contentsOfFile: path) {
// Use your myDict here
for case let category as NSDictionary in array {
categoryDict[category.object(forKey: "code") as! Int] = category.object(forKey: "name") as? String
}
}
changeMonth(value: 0)
}
@IBAction func changeCharts(_ sender: UISegmentedControl) {
drawCharts()
}
@IBAction func previousMonth(_ sender: UIButton) {
changeMonth(value: -1)
}
@IBAction func nextMonth(_ sender: UIButton) {
changeMonth(value: 1)
}
func changeMonth(value: Int) {
currentMonth = currentMonth + value
if currentMonth > 12 {
currentMonth = 1
currentYear = currentYear + 1
} else if currentMonth < 1 {
currentMonth = 12
currentYear = currentYear - 1
}
calendarTitle.text = "\(currentYear) " + monthTitle[currentMonth - 1]
}
func drawCharts() {
showView.subviews.forEach({ $0.removeFromSuperview()})
if chartsType.selectedSegmentIndex == 0 {
// 心情 長條圖
// 水、運動 複合圖(長條加折線)
showView.addSubview(dayMoodChart)
showView.addSubview(dayWaterExerciseChart)
} else if chartsType.selectedSegmentIndex == 1 {
// Event分類圓餅圖
showView.addSubview(eventCategoryChart)
}
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
}
這樣今天就完成囉!明天把程式碼撈取資料和產生圖表的部分完成就大功告成!