[swift] FSCalendar에서 특정 날짜의 이벤트 개수 표시

FSCalendar는 iOS 앱에서 캘린더 기능을 구현하는 데 유용한 오픈 소스 라이브러리입니다. 이 라이브러리를 사용하여 특정 날짜에 이벤트 개수를 표시하는 방법을 알아보겠습니다.

1. FSCalendarDelegate 메소드 구현

FSCalendarDelegate 프로토콜을 채택한 뒤, 다음과 같은 메소드를 구현합니다.

func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
    // 이벤트 개수를 지정하는 로직을 구현합니다.
    // 예를 들어, 특정 날짜의 이벤트 개수를 반환합니다.
    let eventCount = // 이벤트 개수를 계산하는 로직
    return eventCount
}

위의 메소드에서는 특정 날짜의 이벤트 개수를 반환하는 로직을 구현해야 합니다. 예를 들어, 데이터베이스에서 해당 날짜에 저장된 이벤트 개수를 가져오거나, 서버 API를 호출하여 이벤트 개수를 가져올 수 있습니다.

2. FSCalendar 객체에 delegate 설정

FSCalendar 객체를 생성한 뒤, delegate를 설정합니다.

let calendar = FSCalendar()
calendar.delegate = self

3. 이벤트 개수 표시하기

FSCalendar에서 특정 날짜의 이벤트 개수를 표시하는 방법은 다양합니다. 예를 들어, 날짜 아래에 빨간 동그라미로 이벤트 개수를 표시하는 방법을 알아보겠습니다.

func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
    let cell = calendar.dequeueReusableCell(withIdentifier: "cell", for: date, at: position)
    
    let eventCount = calendar.dataSource?.calendar(calendar, numberOfEventsFor: date) ?? 0
    if eventCount > 0 {
        let eventLabel = UILabel(frame: CGRect(x: 0, y: cell.bounds.height - 20, width: cell.bounds.width, height: 20))
        eventLabel.text = "\(eventCount)개의 이벤트"
        eventLabel.textAlignment = .center
        eventLabel.textColor = .red
        eventLabel.font = UIFont.boldSystemFont(ofSize: 12)
        cell.addSubview(eventLabel)
    }
    
    return cell
}

위의 메소드에서는 cellFor 메소드를 이용하여 특정 날짜의 셀을 가져온 뒤, 이벤트 개수를 확인하고 이벤트 개수를 표시하는 UILabel을 추가합니다. 여기서 “cell”은 셀의 재사용 식별자입니다. 이 식별자를 재활용 가능한 셀에 설정해야 합니다.

참고 자료