[swift] FSCalendar에서 날짜 선택에 따른 이벤트 리스트 표시

FSCalendar는 iOS 앱에서 달력 기능을 구현할 수 있는 강력한 라이브러리입니다. 이것은 사용자가 날짜를 선택할 때 이벤트를 표시하고 관리하는 기능을 제공합니다. 이번 블로그 포스트에서는 FSCalendar를 사용하여 날짜 선택에 따른 이벤트 리스트를 표시하는 방법을 소개하겠습니다.

1. FSCalendar 라이브러리 설치

FSCalendar를 사용하기 위해서는 CocoaPods를 통해 라이브러리를 설치해야 합니다.

  1. Podfile 파일을 열고 아래 코드를 추가합니다.
pod 'FSCalendar'
  1. 터미널에서 아래 명령을 실행하여 pod을 설치합니다.
$ pod install
  1. 프로젝트의 .xcworkspace 파일을 열어서 FSCalendar를 사용할 준비가 됩니다.

2. FSCalendar 사용 준비

2.1 FSCalendarDelegateFSCalendarDataSource 프로토콜을 채택하는 클래스를 생성합니다.

import UIKit
import FSCalendar

class CalendarViewController: UIViewController, FSCalendarDelegate, FSCalendarDataSource {

    @IBOutlet weak var calendar: FSCalendar!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        calendar.delegate = self
        calendar.dataSource = self
        
        // 이벤트 데이터 설정
        // ...
    }
}

2.2 calendar.delegatecalendar.dataSourceself로 설정하여 뷰 컨트롤러가 FSCalendar의 delegate와 dataSource 역할을 할 수 있도록 합니다.

3. 이벤트 데이터 설정

3.1 이벤트 데이터를 관리하기 위해 Dictionary를 사용합니다. 날짜를 key로 하고 해당 날짜에 발생하는 이벤트를 value로 합니다.

var eventDict: [String: [String]] = [:]

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 이벤트 데이터 설정
    eventDict["2022-01-01"] = ["New Year's Day"]
    eventDict["2022-12-25"] = ["Christmas Day"]
    // ...
}

3.2 FSCalendar의 이벤트 데이터를 설정하기 위해 FSCalendarDataSource 프로토콜의 calendar(_:numberOfEventsFor:) 메서드를 구현합니다.

func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
    let dateString = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)
    return eventDict[dateString]?.count ?? 0
}

3.3 이벤트 데이터를 표시하기 위해 FSCalendarDelegate 프로토콜의 calendar(_:willDisplay:event:for:) 메서드를 구현합니다.

func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at monthPosition: FSCalendarMonthPosition) {
    let dateString = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)
    let events = eventDict[dateString] ?? []
    
    if events.isEmpty {
        cell.eventIndicator.isHidden = true
    } else {
        cell.eventIndicator.isHidden = false
        cell.eventIndicator.numberOfEvents = events.count
    }
}

4. 이벤트 리스트 표시

4.1 날짜를 선택했을 때 이벤트 리스트를 표시하기 위해 FSCalendarDelegate 프로토콜의 calendar(_:didSelect:) 메서드를 구현합니다.

func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
    let dateString = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)
    let events = eventDict[dateString] ?? []

    if !events.isEmpty {
        showAlert(with: events)
    }
}

func showAlert(with events: [String]) {
    let alert = UIAlertController(title: "Events", message: events.joined(separator: "\n"), preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    present(alert, animated: true, completion: nil)
}

4.2 선택한 날짜에 대한 이벤트가 있을 경우, showAlert(with:) 메서드를 호출하여 이벤트 리스트를 알림으로 표시합니다.

이제 FSCalendar를 사용하여 날짜 선택에 따른 이벤트 리스트를 표시하는 기능을 구현할 수 있습니다. 선택한 날짜에 따라 이벤트를 표시하고 관리하는 방법에 대해 알아보았습니다. 이것은 앱에서 달력 기능을 구현하고 사용자에게 유용한 정보를 제공하는데 도움이 될 것입니다.

참고 자료