生成过去30天的X轴值

时间:2018-03-08 17:06:47

标签: swiftcharts

我能够为特定月份(即二月份)生成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轴值?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,首先是在日期进行扩展:

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