0

我正在制作计步器并使用 luispadron 的 UICircularProgressRing。我正在尝试更新我的 circularProgressRing 以将环的当前状态显示为用户在 7 天 lineChart 中选择的状态。例如:用户点击图表上的值 2309(steps),然后 circularProgressRing 更新以显示 2309 步。

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
      let generator = UISelectionFeedbackGenerator()
          generator.selectionChanged()
    print(self.circularProgressRing.value = CGFloat(1000))

这会将 circularProgressRing 更新为 1000 并且运行良好。现在的问题是如何在 updateStepsWeekly(completion: @escaping (Double) -> Void) 中获取 7 天的步长值,并根据用户对不同值的点击来更新 circularProgressRing?

//Get Steps from HealthKit and Graph daily steps for past 7 days
func updateStepsWeekly(completion: @escaping (Double) -> (Void)) {

        let calendar = NSCalendar.current

        let interval = NSDateComponents()
        interval.day = 1

        // Set the anchor date to Monday at 3:00 a.m.
        var anchorComponents = calendar.dateComponents([.year, .month, .day], from: Date())

    anchorComponents.hour = 0
            guard let anchorDate = calendar.date(from: anchorComponents)
             else {
                fatalError("*** unable to create a valid date from the given components ***")
            }

            guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else {
                fatalError("*** Unable to create a step count type ***")
            }
            // Create the query
    let query = HKStatisticsCollectionQuery(quantityType: quantityType, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: interval as DateComponents)
        // Set the results handler
        query.initialResultsHandler = {query, results, error in
            guard results != nil else {
                            // Perform proper error handling here
                            fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
                        }
            let endDate = Date()
             guard let startDate = calendar.date(byAdding: .day, value: -6, to: endDate as Date)
                         else {
                            fatalError("*** Unable to calculate the start date ***")
                        }
             //Plot the daily step counts over the past 7 days
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "E"

            results?.enumerateStatistics(from: startDate, to: endDate){[unowned self] statistics, stop in

                let date = statistics.startDate
                let value: Double
                if let quantity = statistics.sumQuantity() {

                    value = quantity.doubleValue(for: HKUnit.count())

                    print("\(date): \(value)")
                } else {
                    value = 0
                }

                self.numbers.append(value)
                let dayOfTheWeekString = dateFormatter.string(from: date)
                self.days.append(dayOfTheWeekString)

            }
            //Wait for the numbers array to append all 7 values
            DispatchQueue.main.async {
                self.updateGraph(numbers: self.numbers)
                self.numbers.removeAll()
                self.days.removeAll()

                    }

            }

    self.healthStore.execute(query)
        }

这是在 updateStepsWeekly 中调用的图形函数:

func updateGraph(numbers: [Double]) {

    var lineChartEntry = [ChartDataEntry]()
    let gradientColors = [UIColor.orange.cgColor, UIColor.clear.cgColor] as CFArray
    let colorLocations:[CGFloat] = [0.5, 0.0]
    let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations)
    let marker: BalloonMarker = BalloonMarker(color: UIColor(red: 93/255, green: 186/255, blue: 215/255, alpha: 0), font: UIFont(name: "HelveticaNeue-Medium", size: 12)!, textColor: UIColor.white, insets: UIEdgeInsets(top: 7.0, left: 7.0, bottom: 25.0, right: 7.0))
        marker.minimumSize = CGSize(width: 35.0, height: 35.0)
    let fontType = UIFontDescriptor(name: "HelveticaNeue-Medium", size: CGFloat(15.0))
    let xAxis: XAxis = self.lineChart.xAxis
        xAxis.labelFont = UIFont(descriptor: fontType, size: CGFloat(13.0))

    for i in 0..<numbers.count {
        let value = ChartDataEntry(x: Double(i), y: Double(numbers[i]))
        lineChartEntry.append(value)

        }

    let line1 = LineChartDataSet(entries: lineChartEntry, label: "Days")


            line1.drawValuesEnabled = true
            line1.valueColors = [NSUIColor.white]
            line1.valueTextColor = NSUIColor.clear
            line1.colors = [NSUIColor.orange]
            line1.drawCircleHoleEnabled = true
            line1.circleRadius = CGFloat(5)
            line1.circleHoleRadius = CGFloat(0)
            line1.circleHoleColor = NSUIColor.yellow
            line1.circleColors = [NSUIColor.systemYellow]
            line1.lineWidth = CGFloat(5)
            line1.fill = Fill.fillWithLinearGradient(gradient!, angle: 90.0) // Set the Gradient
            line1.drawFilledEnabled = true
            line1.drawHorizontalHighlightIndicatorEnabled = false
            line1.drawVerticalHighlightIndicatorEnabled = false
            line1.highlightLineWidth = CGFloat(0.3)
            line1.highlightColor = NSUIColor.white
            line1.mode = .cubicBezier
            line1.cubicIntensity = CGFloat(0.17)

            lineChart.drawGridBackgroundEnabled = true
            lineChart.gridBackgroundColor = NSUIColor.black
            lineChart.drawBordersEnabled = false
            lineChart.backgroundColor = UIColor.black
            lineChart.noDataText = ""
            lineChart.legend.enabled = false
            lineChart.extraLeftOffset = 20
            lineChart.extraRightOffset = 20
            lineChart.isMultipleTouchEnabled = false
            lineChart.isUserInteractionEnabled = true

            lineChart.pinchZoomEnabled = false
            lineChart.dragEnabled = true
            lineChart.dragXEnabled = true
            lineChart.dragYEnabled = true
            lineChart.scaleXEnabled = false
            lineChart.scaleYEnabled = false
            lineChart.doubleTapToZoomEnabled = false
            lineChart.highlightPerDragEnabled = true
            lineChart.highlightPerTapEnabled = true
            lineChart.marker = marker
            lineChart.resetViewPortOffsets()
            lineChart.minOffset = CGFloat(0)

            lineChart.leftAxis.labelTextColor = UIColor.white
            lineChart.leftAxis.drawLabelsEnabled = false
            lineChart.leftAxis.drawGridLinesEnabled = false
            lineChart.leftAxis.drawAxisLineEnabled = false
            lineChart.leftAxis.removeAllLimitLines()
            lineChart.leftAxis.drawZeroLineEnabled = false
            lineChart.leftAxis.drawLimitLinesBehindDataEnabled = false

            lineChart.rightAxis.drawLabelsEnabled = false
            lineChart.rightAxis.drawGridLinesEnabled = false
            lineChart.rightAxis.drawAxisLineEnabled = false
            lineChart.rightAxis.removeAllLimitLines()
            lineChart.rightAxis.drawZeroLineEnabled = false
            lineChart.rightAxis.drawLimitLinesBehindDataEnabled = false

            lineChart.xAxis.labelTextColor = UIColor.white
            lineChart.xAxis.labelPosition = .bottom
            lineChart.xAxis.valueFormatter = self
            lineChart.xAxis.drawGridLinesEnabled = false
            lineChart.xAxis.drawAxisLineEnabled = true
            let dashLength:[CGFloat] = [2.0]
            lineChart.xAxis.axisLineDashPhase = CGFloat(1)
            lineChart.xAxis.axisLineDashLengths = dashLength
            lineChart.xAxis.drawLabelsEnabled = true
            lineChart.xAxis.drawLimitLinesBehindDataEnabled = false
            lineChart.xAxis.granularityEnabled = true
            lineChart.xAxis.granularity = 1
            lineChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: days)
            if lineChart.isDragDecelerationEnabled {
                line1.drawVerticalHighlightIndicatorEnabled = true
                }

            let data = LineChartData()
            data.addDataSet(line1)
            lineChart.data = data
            lineChart.notifyDataSetChanged()
}

截图:https ://i.stack.imgur.com/XJmpm.png

4

1 回答 1

0

我所要做的就是将条目的 y 值放入 circularProgressRing

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
      let generator = UISelectionFeedbackGenerator()
          generator.selectionChanged()

            self.circularProgressRing.value = CGFloat(entry.y)



   }
于 2020-04-25T04:19:15.623 回答