Обновить значение CircularProgressRing до значений, выбранных на 7-дневном графике - PullRequest
0 голосов
/ 25 апреля 2020

Я делаю шагомер и использую UICircularProgressRing от luispadron. Я пытаюсь обновить мой циркулярный прогресс, чтобы показать текущее состояние кольца в соответствии с тем, что выбрал пользователь на 7-дневной линейной диаграмме. Например: пользователь нажимает на значение 2309 (шагов) на диаграмме, затем циркулярный ProProRRING обновляет, показывая 2309 шагов.

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

Это обновит циркулярный прогресс по кольцу до 1000 и будет работать хорошо. Теперь вопрос в том, как мне получить 7-дневные значения шага внутри updateStepsWeekly (завершение: @escaping (Double) -> Void) и обновить циркулярный прогресс на основе нажатия пользователем другого значения?

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

1 Ответ

0 голосов
/ 25 апреля 2020

Все, что мне нужно было сделать, это поместить значение y записи в RoundProgressRing

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

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



   }
...