簡體   English   中英

更改選項卡時清除視圖數據 SwiftUI

[英]Clear View Data When Tab is Changed SwiftUI

我在其中一個選項卡中顯示每日步數信息。 不幸的是,當我再次選擇步驟選項卡時,它會在前一個下方添加一個相同的數據。

在此處輸入圖片說明

我試圖通過切換布爾值來解決它。 但它也沒有幫助。

import SwiftUI
import HealthKit

struct StepView: View {
    private var healthStore: HealthStore?
    @State private var presentClipboardView = true
    @State private var steps: [Step] = [Step]()
    init() {
        healthStore = HealthStore()
    }
    private func updateUIFromStatistics(_ statisticsCollection: HKStatisticsCollection) {
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        statisticsCollection.enumerateStatistics(from: startOfDay, to: now) { (statistics, stop) in
            let count = statistics.sumQuantity()?.doubleValue(for: .count())
            let step = Step(count: Int(count ?? 0), date: statistics.startDate, wc: Double(count ?? 0 / 1000 ))
            steps.append(step)
        }
    }
    var body: some View {  
        VStack {
            ForEach(steps, id: \.id) { step in
                VStack {
                        HStack{
                            Text("WC")
                            Text("\(step.wc)")
                        }
                        HStack {
                            Text("\(step.count)")
                            Text("Total Steps")
                        }
                        Text(step.date, style: .date)
                            .opacity(0.5)
                        Spacer()
                }
            }
            .navigationBarBackButtonHidden(true)
        }
        .onAppear() {
            if let healthStore = healthStore {
                healthStore.requestAuthorization { (success) in
                    if success {
                        healthStore.calculateSteps { (statisticsCollection) in
                            if let statisticsCollection = statisticsCollection {
                                updateUIFromStatistics(statisticsCollection)
                            }
                        }
                    }
                }
            }
        }
        .onDisappear() {
            self.presentClipboardView.toggle()
        }
    }
}

階梯模型

struct Step: Identifiable {
    let id = UUID()
    let count: Int?
    let date: Date
    let wc: Double
}

健康存儲文件

class HealthStore {
    var healthStore: HKHealthStore?
    var query: HKStatisticsCollectionQuery?
    init() {
        if HKHealthStore.isHealthDataAvailable() {
            healthStore = HKHealthStore()
        }
    }
    func calculateSteps(completion: @escaping (HKStatisticsCollection?) -> Void ) {
        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let daily = DateComponents(day:1)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: Date(), options: .strictStartDate)
        query = HKStatisticsCollectionQuery(quantityType: stepType, quantitySamplePredicate: predicate, options: .cumulativeSum, anchorDate: startOfDay, intervalComponents: daily)
        query!.initialResultsHandler = { query, statisticCollection, error in
            completion(statisticCollection)
        }
        if let healthStore = healthStore, let query = self.query {
            healthStore.execute(query)
        }
    }
    
    func requestAuthorization(completion: @escaping (Bool) -> Void) {
        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
        guard let healthStore = self.healthStore else { return completion (false) }
        healthStore.requestAuthorization(toShare: [], read: [stepType]) { (success, error) in
            completion(success)
        }
    }
}

根據我的問題,這些都是相關文件。 提前致謝。

這些steps@State注釋,這意味着即使重新繪制視圖,它也會被持久化。

你永遠不會重置它。 您只需添加新步驟。 嘗試清除updateUIFromStatistics steps

private func updateUIFromStatistics(_ statisticsCollection: HKStatisticsCollection) {
    steps = [] // remove previous values
    let now = Date()
    let startOfDay = Calendar.current.startOfDay(for: now)
    statisticsCollection.enumerateStatistics(from: startOfDay, to: now) { (statistics, stop) in
        let count = statistics.sumQuantity()?.doubleValue(for: .count())
        let step = Step(count: Int(count ?? 0), date: statistics.startDate, wc: Double(count ?? 0 / 1000 ))
        steps.append(step)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM