0

我正在尝试使用直接编写的方法在 Xcode 中为我的预览生成一些模拟数据,ContentView_Previews但我没有成功,我不明白为什么。

struct ContentView_Previews: PreviewProvider {
    static let healthManager = generateMockData()
    
    static var previews: some View {
        MainView().environmentObject(healthManager)
    }
    
    static func generateMockData() -> HealthManager {
        let defaultHealthManager = HealthManager()
        defaultHealthManager.gavePermissions = true
        
        for i in 1...10 {
            let defaultWorkout = HKWorkout(activityType: .traditionalStrengthTraining,
                                           start: .now - Double(i * 50),
                                           end: .now,
                                           duration: Double(i * 100),
                                           totalEnergyBurned: HKQuantity(unit: .largeCalorie(), doubleValue: Double(i * 100)),
                                           totalDistance: nil,
                                           device: nil,
                                           metadata: nil)
            
            defaultHealthManager.previousWorkouts.append(defaultWorkout)
        }
        
        
        return defaultHealthManager
    }
}

基本上它显示defaultHealthManager对象除了默认值之外没有设置任何值。如果我ContentView_Previews. generateMockData()在运行时在实际视图中调用我的属性,它工作正常。

4

1 回答 1

1

有时,我似乎需要创建我所谓的中间视图来让事情正常进行。这样的事情有用吗?

struct MainViewIntermediary: View {
    @State var healthManager: HealthManager

    init() {
        let defaultHealthManager = HealthManager()
        defaultHealthManager.gavePermissions = true
        
        for i in 1...10 {
            let defaultWorkout = HKWorkout(activityType: .traditionalStrengthTraining,
                                           start: .now - Double(i * 50),
                                           end: .now,
                                           duration: Double(i * 100),
                                           totalEnergyBurned: HKQuantity(unit: .largeCalorie(), doubleValue: Double(i * 100)),
                                           totalDistance: nil,
                                           device: nil,
                                           metadata: nil)
            
            defaultHealthManager.previousWorkouts.append(defaultWorkout)
            _healthManager = State(initialValue: defaultHealthManager)
        }
    }

   var body: some View {
        MainView().environmentObject(healthManager)
    }
}

然后您的预览提供者变为:

struct ContentView_Previews: PreviewProvider {
    
    static var previews: some View {
        MainViewIntermediary()
    }
}
于 2022-02-07T20:21:41.297 回答