iosswiftcalendarfscalendar

Update FSCalendar Header value with select date swift


I have set FSCalendar scope mode as week. After that Header date format I have set calendar.appearance.headerDateFormat = "dd MMMM yyyy EEEE" and it's showing correct format.

Code and Image added.

func setupFSCalendar() {

        ViewCalendar.frame = CGRect(x: 0, y: 78, width: view.frame.width, height: 100)
        ViewCalendar.backgroundColor = ("#455a64").toColor()
        let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: ViewCalendar.frame.width, height: 250))
        calendar.layoutIfNeeded()
        calendar.dataSource = self
        calendar.delegate = self
        calendar.appearance.weekdayTextColor = .white  // week name color
        calendar.appearance.headerDateFormat = "dd MMMM yyyy EEEE"
        calendar.appearance.headerTitleColor = UIColor.white
        calendar.appearance.headerTitleFont = UIFont.systemFont(ofSize: 12)
        calendar.appearance.titleWeekendColor = UIColor.white
        
        calendar.appearance.titleDefaultColor =  .white
        calendar.scrollDirection = .horizontal
        
        calendar.appearance.weekdayFont = UIFont.systemFont(ofSize: 12)
        calendar.appearance.titleFont = UIFont.systemFont(ofSize: 18)
        calendar.appearance.titleTodayColor = ("#54a767").toColor()
        calendar.appearance.selectionColor  = ("#788f9b").toColor()
        calendar.appearance.todayColor = nil
        
        calendar.appearance.subtitleWeekendColor = UIColor.white
        calendar.placeholderType = .none   /// to remove last month dates
        calendar.appearance.headerMinimumDissolvedAlpha = 0   // removes next prev month title.
        calendar.backgroundColor = .clear 
        
        calendar.firstWeekday = 2
        calendar.scope = .week
        
        ViewCalendar.addSubview(calendar)
    }


    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        print(date)
        calendar.setCurrentPage(date, animated: true)
        calendar.select(date)
        
    }

FSCalendar


Solution

  • You can do this by replacing the text of visible FSCalendarHeaderCells from the selected date as below

    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        print(date)
        calendar.setCurrentPage(date, animated: true)
        calendar.select(date)
        
        //format the selectedDate and set to the header
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = calendar.appearance.headerDateFormat
        
        for cell in calendar.calendarHeaderView.collectionView.visibleCells {
            (cell as! FSCalendarHeaderCell).titleLabel.text = dateFormatter.string(from: date)
        }
    }
    

    enter image description here