• class ViewController 放入
  • 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)

  • 重写 viewWillAppear,在画面每次出现前执行从 UserDefaults 取得先前设定的显示年月字串,如果有值则用 DateFormatter 将其转换为日期,并更新 currentDate更新后将 "displayYearMonth" 清空,以免重复使用
  • 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 中的资料
    }

  • func updateRecordsList()放入
  • // 设定日期格式为 "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)

  • 切换月份,传入一个 DateComponents(例如 month 改变 ±1),透过 Calendar 计算新的日期,更新 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()
    }