티스토리 뷰

이번 달 달력 표시하기

커스텀 셀

이번 달 달력을 표시해주기 위하여 CalendarCollectionViewCellconfigure()를 수정하겠습니다.

self.dayLabel.text = "0"

dayLabel의 텍스트를 "0"으로 설정해주는 코드를 삭제합니다.

    private func configure() {
        self.addSubview(self.dayLabel)
        self.dayLabel.font = .boldSystemFont(ofSize: 12)
        self.dayLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.dayLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5),
            self.dayLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor)
        ])
    }

그럼 configure()가 위와 같아지겠죠?

    func update(day: String) {
        self.dayLabel.text = day
    }

그다음 위의 메서드를 추가해줍니다.
day로 들어오는 문자열로 dayLabel을 설정해주는 코드입니다!

 

뷰 컨트롤러

이제 ViewController로 돌아오겠습니다.

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.days.count
    }

numberOfItemsInSection을 수정해주겠습니다.
days에 있는 값으로 셀을 설정해주기 위해 위의 코드처럼 self.days.count로 바꿔줍니다.

2022년 1월 기준으로 days에 37개의 값이 들어가 있으니 37개의 셀이 생성되겠네요.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CalendarCollectionViewCell.identifier, for: indexPath) as? CalendarCollectionViewCell else { return UICollectionViewCell() }
        cell.update(day: self.days[indexPath.item])
        return cell
    }

그다음 커스텀 셀에서 만들어 둔 update(day:)cellForItemAt에서 불러주겠습니다.

self.days[indexPath.item]을 통하여 0번부터 36번까지 days에 접근하여 문자열을 가져와 update(day:)에 넣어주게 됩니다.
update(day:)dayLabel을 받은 문자열로 설정하게 되겠죠?

여기까지 하고 실행해보니 이번 달 달력이 화면에 잘 표시되네요!



버튼 기능 구현하기

이전 달, 다음 달 이동하기

    @objc private func didPreviousButtonTouched(_ sender: UIButton) {
        self.minusMonth()
    }

    @objc private func didNextButtonTouched(_ sender: UIButton) {
        self.plusMonth()
    }

위의 코드를 ViewController에 추가해줍니다.
didPreviousButtonTouched()에서는 minusMonth()didNextButtonTouched()에서는 plusMonth()를 불러줍니다.

이제 이 코드를 버튼에 적용해야겠죠?

    private func configurePreviousButton() {
        self.contentView.addSubview(self.previousButton)
        self.previousButton.tintColor = .label
        self.previousButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        self.previousButton.addTarget(self, action: #selector(self.didPreviousButtonTouched), for: .touchUpInside)
        self.previousButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.previousButton.widthAnchor.constraint(equalToConstant: 44),
            self.previousButton.heightAnchor.constraint(equalToConstant: 44),
            self.previousButton.trailingAnchor.constraint(equalTo: self.titleLabel.leadingAnchor, constant: -5),
            self.previousButton.centerYAnchor.constraint(equalTo: self.titleLabel.centerYAnchor)
        ])
    }

addTarget()을 이용하여 .touchUpInside가 됐을 때 didPreviousButtonTouched()를 부르도록 지정해주면 됩니다.
아무 데나 해당 코드를 넣어도 되지만 저는 configurePreviousButton()에 넣어주었습니다.

self.nextButton.addTarget(self, action: #selector(self.didNextButtonTouched), for: .touchUpInside)

nextButton에도 addTarget()을 해줍니다.

실행해보면 이전 달, 다음 달 버튼이 잘 작동할 것입니다!

 

이번 달로 이동하기

달력 하면 빠질 수 없는 이번 달로 이동하는 기능을 구현해보겠습니다.

private func configureCalendar() { 
    let components = self.calendar.dateComponents([.year, .month], from: Date()) 
    self.calendarDate = self.calendar.date(from: components) ?? Date() 
    self.dateFormatter.dateFormat = "yyyy년 MM월" 
    self.updateCalendar() 
}

위의 코드는 기존의 configureCalendar()입니다.

초기 설정에서 calendarDate, dateFormatter를 설정해준 후 updateCalendar()를 불러주는데,
이번 달로 이동할 때 calendarDate 설정 후 updateCalendar()를 불러주어야 해서 3줄의 코드가 중복됩니다.

중복되는 코드를 작성하기는 싫으니 configureCalendar()를 분리하겠습니다.

    private func today() {
        let components = self.calendar.dateComponents([.year, .month], from: Date())
        self.calendarDate = self.calendar.date(from: components) ?? Date()
        self.updateCalendar()
    }

today() 메서드를 추가한 후 초기 설정과 이번 달 이동 기능의 중복되는 코드를 분리시켜줍니다.

    private func configureCalendar() {
        self.dateFormatter.dateFormat = "yyyy년 MM월"
        self.today()
    }

configureCalendar()에서 today()를 불러주면 분리 전과 같은 동작을 하게 됩니다.

이제 today()를 이용하여 todayButton의 기능을 추가해보겠습니다.

    @objc private func didTodayButtonTouched(_ sender: UIButton) {
        self.today()
    }

didTodayButtonTouched()를 추가한 후 여기서도 today()를 불러줍니다.

self.todayButton.addTarget(self, action: #selector(self.didTodayButtonTouched), for: .touchUpInside)

addTarget()만 해주면 이번 달로 이동하는 기능도 완성입니다.

 


 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함