[swift] FSCalendar에서 특정 날짜의 이벤트 액션 데이터 저장 설정

FSCalendar은 iOS 앱에서 캘린더 기능을 구현하기 위한 라이브러리입니다. 이 라이브러리를 사용하여 특정 날짜의 이벤트를 저장하고 해당 이벤트에 대한 액션을 설정하는 방법을 알아보겠습니다.

이벤트 데이터 저장하기

FSCalendar에서는 이벤트 데이터를 저장하기 위해 eventSource라는 프로퍼티를 사용합니다. 이 프로퍼티는 FSCalendarEventSource 프로토콜을 따르는 객체를 할당합니다. 이 객체는 이벤트 데이터를 반환하는 메서드를 구현해야 합니다.

다음은 FSCalendarEventSource 프로토콜을 구현한 예제입니다.

class EventSource: NSObject, FSCalendarEventSource {
    var events: [Date: [String]] = [:]
    
    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
        return events[date]?.count ?? 0
    }
    
    func calendar(_ calendar: FSCalendar, eventFor date: Date) -> FSCalendarEvent? {
        guard let eventNames = events[date] else {
            return nil
        }
        
        let event = FSCalendarEvent()
        event.identifier = "\(date)"
        event.title = eventNames.joined(separator: ", ")
        return event
    }
    
    func addEvent(_ eventName: String, for date: Date) {
        if events[date] == nil {
            events[date] = []
        }
        events[date]?.append(eventName)
        calendar.reloadData()
    }
}

EventSource 클래스는 FSCalendarEventSource 프로토콜을 따르며, events라는 딕셔너리를 사용하여 날짜별로 이벤트 데이터를 저장합니다. addEvent 메서드를 사용하여 특정 날짜에 이벤트를 추가할 수 있습니다.

이벤트 액션 설정하기

특정 날짜의 이벤트에 대한 액션을 설정하기 위해서는 FSCalendarDelegate 프로토콜의 calendar:didSelectDate:at monthPosition: 메서드를 구현합니다. 이 메서드는 사용자가 특정 날짜를 선택할 때 호출됩니다.

다음은 이벤트 액션을 설정하는 예제입니다.

class ViewController: UIViewController, FSCalendarDelegate {
    let eventSource = EventSource()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        calendar.delegate = self
    }
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        let eventNames = eventSource.events[date] ?? []
        if !eventNames.isEmpty {
            // 특정 날짜의 이벤트에 대한 액션 처리
            // 예: 이벤트 목록 표시, 이벤트 상세 보기 등
        }
    }
}

ViewController 클래스는 FSCalendarDelegate 프로토콜을 따르며, eventSource라는 이벤트 데이터 소스 객체를 생성하고 할당합니다. calendar(_:didSelect:at:) 메서드를 사용하여 특정 날짜의 이벤트에 대한 액션을 처리할 수 있습니다.

이제 FSCalendar를 사용하여 특정 날짜의 이벤트를 저장하고 액션을 설정하는 방법을 알게 되었습니다. 더 자세한 내용은 FSCalendar 공식 문서를 참조하시기 바랍니다.