0

我能够为一个特定的月份(即二月)生成 X 轴。

    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
        }
    }

但我想在过去 30 天内拉伸 X 轴值;不只是一个月。如何生成过去 30 天的 X 轴值?

4

1 回答 1

0

我首先通过在 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
    }
}

然后我用它来生成 x 轴日期:

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
    }
}
于 2018-03-08T19:33:30.493 回答