Swift

iOS Cutsom Calendar 구현하기 4

Thor_yeom 2023. 4. 18. 20:44

마지막을 향해 달려가고 있습니다. 

 

오늘 할 것은

버튼을 눌렀을때 액션을 만들어 줄겁니다. 

 

1) previousButton Clicked 액션 만들기

extension 안에 

    // 이전 달로 가는 메서드
    func minusMonth() {
        // date(byAdding: ~ ) 지정된 날짜에 구성요소를 추가하여 계산된 날짜를 반환 메소드
        calendarDate = calendar.date(byAdding: DateComponents(month: -1), to: calendarDate) ?? Date()
        updateCalendar()
    }

 

DateComponents에 대한 내용을 보면 

DateComponents을 활용하여 시간대를 설정 할 수있습니다.

공식문서 출처

 

2) previoutButton에 addtarget을 통해 액션 메서드를 만듭니다.

    var previousButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        button.setTitleColor(.label, for: .normal)
        button.addTarget(self, action: #selector(previousButtonClicked), for: .touchUpInside)
        return button
    }()

addtarget은 만들어졌고 #selector() 메서드에 들어갈 액션 메서드를 만듭니다.

    // MARK: - Action Method
    @objc func previousButtonClicked() {
        minusMonth()
    }

 

다음 달 만드는 거는 너무 쉽겠죠?

 

3) plusMonth() 메서드를 만들어 줍니다.

    // 다음 달로 가는 메서드
    func plusMonth() {
        // date(byAdding: ~ ) 지정된 날짜에 구성요소를 추가하여 계산된 날짜를 반환 메소드
        calendarDate = calendar.date(byAdding: DateComponents(month: 1), to: calendarDate) ?? Date()
        updateCalendar()
    }

 

4) nextButton에 addtarget을 만들어주고 액션 함수를 만듭니다.

    var nextButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: "chevron.right"), for: .normal)
        button.addTarget(self, action: #selector(nextButtonClicked), for: .touchUpInside)
        button.setTitleColor(.label, for: .normal)
        return button
    }()
    
        @objc func nextButtonClicked() {
        plusMonth()
    }

완성 되었습니다.

 

 

 

그리고 마지막으로  TodayButton을 눌렀을때

현재 달로 이동하는 메서드를 만들어 보겠습니다.

 

5) today() 메소드를 작성해줍니다.

    func today() {
        // dateComponents : 표준 시간대를 사용하여 Calendar의 모든 날짜 구성요소를 반환
        let components = calendar.dateComponents([.year, .month], from: Date())
        // date : 지정된 구성 요소에서 생성된 날짜를 반환
        calendarDate = calendar.date(from: components) ?? Date()
        // Calendar를 업데이트 해줍니다.
        updateCalendar()
    }
    
    func configureCalendar() {
        // 메인 타이틀을 어떤 형식으로 보여줄지 형 변형
        dateFormatter.dateFormat = "yyyy년 MM월"
        // dateComponents : 표준 시간대를 사용하여 Calendar의 모든 날짜 구성요소를 반환
        today()
    }

 

 

6) todayButton에 addtarget을 만들어주고 액션 메서드를 만들어 줍니다.

    var todayButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Today", for: .normal)
        button.backgroundColor = .black
        button.tintColor = .white
        button.layer.cornerRadius = 8
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(todayButtonClicked), for: .touchUpInside)
        return button
    }()
    
   @objc func todayButtonClicked() {
        today()
    }

 

최종 완성본입니다.

 

간단해 보이는 기본 calendar인데도 직접 구현해보니

생각보다 어려웠고, 

다음편에는 본격 Custom calendar로 찾아뵙겠습니다.

 

참고 

https://boreum.tistory.com/65

 

[iOS] Calendar 구조체로 달력 구현하기 (3) - 메서드 구현하기

프로퍼티 private let calendar = Calendar.current private let dateFormatter = DateFormatter() private var calendarDate = Date() private var days = [String]() 먼저 필요한 프로퍼티는 위와 같습니다. 하나씩 설명해 드릴게요! calenda

boreum.tistory.com

https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/

 

UICollectionViewDelegate | Apple Developer Documentation

The methods adopted by the object you use to manage user interactions with items in a collection view.

developer.apple.com

 

'Swift' 카테고리의 다른 글

iOS Custom Calendar 구현하기 5  (0) 2023.04.20
iOS Custom Calendar 구현하기 3  (2) 2023.04.18
iOS Custom Calendar 구현하기2  (0) 2023.04.17
iOS Custom Calender 구현하기  (2) 2023.04.17
어서와 SwiftUI @FetchRequest는 처음이지?  (0) 2023.03.23