Swiftで行こう!--CollectionViewでカレンダー!2
でカレンダーの表示が出来ました。
肝心なカレンダーに表示する月、曜日、日の取得と表示について、もう少し詳しくまとめておきます。復習を含めて。
日付け関係のコードを抜き出します。
let now = Date()
var cal = Calendar.current
let dateFormatter = DateFormatter()
var components = DateComponents()
まず、let now = Date()で今日の日付けの取得します。あとは日付け操作がしやすいように準備、インスタンスを作ります。使い方など詳しいことは
そしてシュミレーター、iPhone起動時のデータ 読み込も時に
cal.locale = Locale(identifier: "ja")
dateFormatter.locale = Locale(identifier: "ja_JP")
dateFormatter.dateFormat = "yyyy年M月"
components.year = cal.component(.year, from: now)
components.month = cal.component(.month, from: now)
components.day = 1
で、今日の"年"、"月"の"1日"に設定します。
func calculation(){
let firstDayOfMonth = cal.date(from: components)
label.text = dateFormatter.string(from: firstDayOfMonth!)
}
ではlabelに表示する関数の定義です。これも起動時に読み込ませるようになっています。
dateFormatter.dateFormat = "yyyy年M月"
のフォーマット、2019年4月というふうに表示されます。
そして表示を行うメインのコードですが、
let firstDayOfMonth = cal.date(from: components)
let firstWeekday = cal.component(.weekday, from: firstDayOfMonth!)
求めたい月の1日を定義から曜日の番号を取得します。
ここで注意することは
曜日の番号です。日曜が1、月曜が2,火曜3、水曜4、木曜5、金曜6、土曜7
ということです。
次にCollectionViewで表示する場合の数字と合わせるために
let weekdayAdding = 2 - firstWeekday
とします。あとのif文
indexPath.row + weekdayAdding
として使います。
for subview in cell.contentView.subviews {
subview.removeFromSuperview()
}
これでいらないとこを消していきます。
次にその月が何日あるかを取得します。
let daysCountInMonth = cal.range(of: .day, in: .month, for: firstDayOfMonth!)?.count
4月だと"30"が取得出来ます。
最後に、CollectionViewに表示させていきます。
if (indexPath.row + weekdayAdding) >= 1 && (indexPath.row + weekdayAdding) <= daysCountInMonth! {
cell.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
let label = UILabel()
label.font = UIFont(name: "Arial", size: 17)
label.text = "\(indexPath.row)"
label.sizeToFit()
label.center = cell.contentView.center
cell.contentView.addSubview(label)
}
let label = UILabel()と定義して、表示する文字の仕様など決めて、cellのcontentViewに追加して表示させます。
あと、条件が合わない場合は空欄にします。
else{
cell.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
全体です。
let firstDayOfMonth = cal.date(from: components)
let firstWeekday = cal.component(.weekday, from: firstDayOfMonth!)
let weekdayAdding = 2 - firstWeekday
for subview in cell.contentView.subviews {
subview.removeFromSuperview()
}
let daysCountInMonth = cal.range(of: .day, in: .month, for: firstDayOfMonth!)?.count
if (indexPath.row + weekdayAdding) >= 1 && (indexPath.row + weekdayAdding) <= daysCountInMonth! {
cell.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.937254902, blue: 0.9568627451, alpha: 1)
let label = UILabel()
label.font = UIFont(name: "Arial", size: 17)
label.text = "\(indexPath.row)"
label.sizeToFit()
label.center = cell.contentView.center
cell.contentView.addSubview(label)
}
else{
cell.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
この記事が気に入ったらサポートをしてみませんか?