0

I'm able to generate the X Axis for one specific month (i.e. February).

    func generateDateAxisValues(_ month: Int, year: Int) -> [ChartAxisValueDate] {
        let date = dateWithComponents(1, month, year)
        let calendar = Calendar.current
        let monthDays = calendar.range(of: .day, in: .month, for: date)!

        let arr = CountableRange<Int>(monthDays)

        return arr.map {day in
            let date = dateWithComponents(day, month, year)
            let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings)
            axisValue.hidden = !(day % 5 == 0)
            return axisValue
        }
    }

But I want to stretch the X Axis values across the past 30 days; not just one individual month. How can you generate X Axis values for the past 30 days?

vikzilla
  • 3,998
  • 6
  • 36
  • 57

1 Answers1

0

I solved this by, first, making an extension on Date:

extension Date {
    var day:Int { return Calendar.current.component(.day, from:self) }
    var month:Int { return Calendar.current.component(.month, from:self) }
    var year:Int { return Calendar.current.component(.year, from:self) }

    func priorDates(daysBack: Int) -> [Date] {
        let cal = Calendar.current
        var date = cal.startOfDay(for: self)
        var dates = [Date]()
        for _ in 1 ... daysBack {
            date = cal.date(byAdding: .day, value: -1, to: date)!
            dates.append(date)
        }
        dates = dates.sorted(by: { $0 < $1 })
        return dates
    }
}

Which I then use to generate the x axis dates:

func generateDateAxisValues(daysBack: Int) -> [ChartAxisValueDate] {
    let priorDaysArray = Date().priorDates(daysBack: daysBack)

    return priorDaysArray.map { date in
        let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings)
        axisValue.hidden = !(date.day % 5 == 0)
        return axisValue
    }
}
vikzilla
  • 3,998
  • 6
  • 36
  • 57