let myFormatter = DateFormatter() // 建立一個 DateFormatter 用來處理日期與字串的轉換
var currentDate :Date = Date() // 定義一個目前日期變數,預設為程式啟動時的當前日期
var days :[String]! = [] // 存放資料庫中每個記錄的日期(字串)
var myRecords :[String:[[String:String]]]! = [:]
// 以日期字串作為 key,對應一個陣列,每個元素是一筆記錄(以字典存放欄位資訊)
var eachDayAmount :[String:Double] = [:] // 以日期作為 key,記錄每天的總計金額
var currentMonthLabel :UILabel! // 當前月份的標籤
(((以下皆在class ViewController內)))
2. override func viewDidLoad() 放入
// 目前年月
currentMonthLabel = UILabel(frame: CGRect(x: 0, y: 0, width: fullsize.width * 0.7, height: 50)) // 建立一個 UILabel 並設定其大小、位置、文字顏色、字型與標籤
currentMonthLabel.center = CGPoint(x: fullsize.width * 0.5, y: 35)
currentMonthLabel.textColor = UIColor.white
myFormatter.dateFormat = "yyyy 年 MM 月" // 使用 DateFormatter 將目前日期格式化成 "yyyy 年 MM 月",顯示在標籤上
currentMonthLabel.text = myFormatter.string(from: currentDate)
currentMonthLabel.textAlignment = .center
currentMonthLabel.font = UIFont(name: "Helvetica Light", size: 32.0)
currentMonthLabel.tag = 701
self.view.addSubview(currentMonthLabel)
override func viewWillAppear(_ animated: Bool) {
let displayYearMonth = myUserDefaults.object(forKey: "displayYearMonth") as? String
if displayYearMonth != nil && displayYearMonth != "" {
myFormatter.dateFormat = "yyyy-MM"
currentDate = myFormatter.date(from: displayYearMonth!)!
myUserDefaults.set("", forKey: "displayYearMonth")
myUserDefaults.synchronize()
}
self.updateRecordsList()
// 呼叫 updateRecordsList() 方法,更新並重新載入 table view 中的資料
}
// 設定日期格式為 "yyyy-MM",將 currentDate 轉換成字串(例如 "2025-02")
myFormatter.dateFormat = "yyyy-MM"
let yearMonth = myFormatter.string(from: currentDate)
// 重新格式化日期顯示,並更新當前月份標籤
myFormatter.dateFormat = "yyyy 年 MM 月"
currentMonthLabel.text = myFormatter.string(from: currentDate)
func updateCurrentDate(_ dateComponents :DateComponents) {
let cal = Calendar.current
let newDate = (cal as NSCalendar).date(byAdding: dateComponents, to: currentDate, options: NSCalendar.Options(rawValue: 0))
currentDate = newDate!
self.updateRecordsList()
}