来月先月を取得する方法です
完成イメージ
DateComponentsを使って現在の年月を表示する
こちらの記事の続きになります。
実装方法
NextLastDateViewModel.swift
class NextLastDateViewModel: ObservableObject {
@Published var text: String = ""
var component: DateComponents
init() {
component = Calendar.current.dateComponents(in: TimeZone.current, from: Date())
text = component.getYearMonthFormat()
}
func onTapNext() {
let calendar = Calendar(identifier: .gregorian)
let date = calendar.date(from: component)!
let addMonth = DateComponents(month: 1, day: 0)
let nextMonth = calendar.date(byAdding: addMonth, to: date)!
component = Calendar.current.dateComponents(in: TimeZone.current, from: nextMonth)
text = component.getYearMonthFormat()
}
func onTapLast() {
let calendar = Calendar(identifier: .gregorian)
let date = calendar.date(from: component)!
let addMonth = DateComponents(month: -1, day: 0)
let lastMonth = calendar.date(byAdding: addMonth, to: date)!
component = Calendar.current.dateComponents(in: TimeZone.current, from: lastMonth)
text = component.getYearMonthFormat()
}
}
コード説明
重要なところだけ説明します。
getYearMonthFormat
については上記記載のあるリンクの前回を確認してください。
DateComponents
を変数で持っておきます。
onTapNext()
は来月のボタンを押したらの処理です。
onTapLast()
は先月のボタンを押したらの処理です。
DateComponents(month: -1, day: 0)
DateComponents(month: 1, day: 0)
こちらで先月、来月にしています。
これを利用すれば来年、明日なども可能になります。
UIは自分で好きなように作成してください!