Search code examples
iosswiftcalendarjtapplecalendar

Showing Months and year as header through JTAppleCalendar


I am using JTAppleCalendar in my iOS application but I am finding it difficult to implement headers that show the month and year at the top of the calendar as a conventional calendar normally would. I have followed instructions in the documentation but I am still finding it difficult despite managing to add 'headers' to show the days of the week albeit I feel maybe not correctly. For anyone who has implemented this library before, can I get some help how to do this? Or maybe another calendar you have used that has an easier way to accomplish this?

I want the screen to look a little like this: enter image description here

While mine currently looks like this: enter image description here

Documentation: https://patchthecode.github.io/Headers/

I implement the days of the week as so:

    // This sets the height of your header
func calendar(_ calendar: JTAppleCalendarView, sectionHeaderSizeFor range: (start: Date, end: Date), belongingTo month: Int) -> CGSize {
    return CGSize(width: 200, height: 50)
}
// This setups the display of your header
func calendar(_ calendar: JTAppleCalendarView, willDisplaySectionHeader header: JTAppleHeaderView, range: (start: Date, end: Date), identifier: String) {
    let headerCell = (header as? PinkSectionHeaderView)
    headerCell?.title.text = "S           M           T           W           T           F           S"
}

Solution

  • I think you just made this a whole lot more difficult than it should be.

    What you saw on the tutorial site was an example Of how you can setup a header with a simple UILabel on it called title. You do not have to follow this exactly if your calendar design is different. Simply design it however you wish.

    It seems that what you want is not a UILabel. You want 7 labels; each representing a day of the week. The easiest way to do this is just to create 7 UILabels inside of a Horizontal Stackiew. StackView's spacing should be set to full and should be set to fill equally. Then all you have to do is click on the individual labels and set their alignment to Center.

    enter image description here

    Make the constraints of the StackView stretch to the ends of the headerView. Done. Your S|M|T|W|T|F|S view is complete without hard coding the spaces; which is a bad thing to do.

    Next it seems you want another 2 labels. One for the Month, and another for the Year. So create those labels in the header view, and then create the outletLets for them. Then you can properly set them up in the following function.

    func calendar(_ calendar: JTAppleCalendarView, willDisplaySectionHeader header: JTAppleHeaderView, range: (start: Date, end: Date), identifier: String) {
    }