Jiwift

[iOS/Swift] JTAppleCalendar 현재 날짜 표시하기 본문

라이브러리/기타

[iOS/Swift] JTAppleCalendar 현재 날짜 표시하기

지위프트 2024. 2. 6. 01:30
반응형

JTAppleCalendar에서 선택과 상관없이 오늘 날짜를 바로 표시하는 방법

오늘 날짜 표시

지난 글 예제를 사용하면 날짜를 선택하는 기능이 있습니다. 이번에는 선택 없이 현재 날짜를 표시하도록 하겠습니다.

 일단 오늘 날짜를 표시하기 위한 View를 Cell 안에 하나 생성합니다. 저는 정사각형으로 생성하였습니다. 그리고 Cell 코드에 IBOutlet을

todayView라는 변수로 연결하였습니다. 

 

 생성한 View는 색상을 지정해 주어서 눈으로 확인 가능하게 합니다. 

 

// DateComponents를 사용하여 두 날짜의 연, 월, 일 부분을 추출합니다.
let components1 = Calendar.current.dateComponents([.year, .month, .day], from: date)
let components2 = Calendar.current.dateComponents([.year, .month, .day], from: Date())

// 두 DateComponents를 비교하여 연, 월, 일 부분이 동일한지 확인합니다.
if components1.year == components2.year &&
   components1.month == components2.month &&
   components1.day == components2.day {
    cell.todayView.isHidden = false
} else {
    cell.todayView.isHidden = true
}

 그리고 JTAppleCalendar의 cellForItemAt에 위와 같이 코드를 작성했습니다. 보시면 오늘 날짜와 calendar의 date를 받아서 연/월/일로 시간을 나누고 비교를 하는 로직입니다. 

 

 만약 생성되는 시점 Cell이 오늘 날짜와 같은 연/월/일이면 todayView를 보여주고 아니면 숨기는 방식입니다. 

 

func calendar(_ calendar: JTACMonthView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTACDayCell {
    let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "LeftRightCellView", for: indexPath) as! LeftRightCellView

    // DateComponents를 사용하여 두 날짜의 연, 월, 일 부분을 추출합니다.
    let components1 = Calendar.current.dateComponents([.year, .month, .day], from: date)
    let components2 = Calendar.current.dateComponents([.year, .month, .day], from: Date())

    // 두 DateComponents를 비교하여 연, 월, 일 부분이 동일한지 확인합니다.
    if components1.year == components2.year &&
       components1.month == components2.month &&
       components1.day == components2.day {
        cell.todayView.isHidden = false
    } else {
        cell.todayView.isHidden = true
    }

    cell.dateLabel.text = cellState.text
    self.calendar(calendar, willDisplay: cell, forItemAt: date, cellState: cellState, indexPath: indexPath)
    return cell
}

cellForItemAt 전체 코드

 

파랑색 : 오늘 날짜 

빨간색 : 선택 날짜

 

  위 방법을 사용하면 날짜를 선택하는 것과 상관없이 오늘 날짜를 표시할 수 있게 됩니다.

 

 

반응형