如何使图表始终显示网格线?

时间:2018-05-10 02:32:51

标签: swift ios-charts

我正在使用图表3.1.1,我无法弄清楚如何使图表始终显示x轴网格线:

enter image description here

在此示例中,我希望图表在4月25日之后显示xAxis网格线和标签,即4月26日,4月27日,4月28日,4月29日,4月30日,5月1日。

我创建了这个类来生成足够的日期,以便在我想要显示的每个后续日期没有数据点时填充空白:

class AxisValuesGenerator: NSObject {
    var days: [String]? = []

    func generatexAxisDates(liftEvents: [LiftEvent]) -> [String]? {
        var dates: [Date] = []
        let intervalBetweenDates: TimeInterval = 3600 * 24 // 3600 = 1 hour
        let firstDate = (liftEvents.first?.date)! // - intervalBetweenDates
        var lastDate = liftEvents.last?.date

        if Double(liftEvents.count) < 7 {
            let daysToAdd = intervalBetweenDates * Double(7 - liftEvents.count)
            lastDate = lastDate?.addingTimeInterval(daysToAdd)
            for _ in 0...6 {
                dates = self.intervalDates(from: firstDate, to: lastDate!, with: intervalBetweenDates)
            }
        } else {
            dates = self.intervalDates(from: firstDate, to: lastDate!, with: intervalBetweenDates)
        }

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM d"

        days = dates.map {dateFormatter.string(from: $0)}

        return days

    }

func intervalDates(from startDate: Date, to endDate:Date, with interval:TimeInterval) -> [Date] {
    guard interval > 0 else { return [] }

    var dates:[Date] = [startDate]
    var currentDate = startDate

    while currentDate <= endDate {
        currentDate = currentDate.addingTimeInterval(interval)
        dates.append(currentDate)
    }

    return dates
}

它会生成我想要的日期:

▿ Optional<Array<String>>   ▿ some : 7 elements
   - 0 : "Apr 25"
   - 1 : "Apr 26"
   - 2 : "Apr 27"
   - 3 : "Apr 28"
   - 4 : "Apr 29"
   - 5 : "Apr 30"
   - 6 : "May 1"
   - 7 : "May 2"

但图表不会显示它们。

如何让图表显示缺失的网格线?

更新:

我已尝试设置setVisibleXRangesetLabelCount(强制),如下所示:

chartView.setVisibleXRange(minXRange: 2.0, maxXRange: 6.0)

let leftAxis = chartView.leftAxis
        leftAxis.setLabelCount(7, force: true)

如果我有6个或更多要绘制的值,图表会正确呈现。但你可以看到,只有2个值,我可以强制行,但xAxis标签是错误的:

enter image description here

0 个答案:

没有答案