我想根据函数输出更新 class 中的信息。我希望这发生.onAppear

I want to update information in a class based on function output. I want this to happen .onAppear

我想在屏幕出现 return of func calloriesPerHour 时更新变量 caloriesPerHour。

我为 .onAppear 代码留下了 space(我假设这就是代码应该去的地方?)

感谢您的帮助。

import Combine
import SwiftUI

这是我要更新的class:

class FastingCalculation: ObservableObject {
    
    @Published var mealSize = 200
    @Published var caloriesPerHour: Int = 70

}

这是我想要的功能运行

func calculateCaloriesPerHour() -> Int {
    let meal = FastingCalculation()
    let user = UserDetails()
    let cPH = user.dailycalories/meal.mealSize
    return cPH
}

struct ContentView: View {
    
    @ObservedObject var lastMeal = FastingCalculation()
    @ObservedObject var userInfo = UserDetails()

我假设这是神奇发生的函数

    func onAppear() {
        // Run calculateCaloriesPerHour function
        // Make var caloriesPerHour = calculateCalroiesPerHour()
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            Text ("Hello \(userInfo.username)")
                .font(.headline)
            
            Text("Enter the size of you last meal:")
                .font(.body)
            
            Picker(selection: $lastMeal.mealSize, label: Text("")) {
                Text("200").tag(200)
                Text("300").tag(300)
                Text("400").tag(400)
                Text("500").tag(500)
                Text("600").tag(600)
                Text("700").tag(700)
                Text("800").tag(800)
                Text("900").tag(900)
                Text("1000").tag(1000)
                Text("1100").tag(1100)
            }
            
            Spacer()
            
            NavigationLink(destination: TimerView()) {
                Text("Start Fasting")
                    .foregroundColor(.blue)
            }
            
        }
    }
}

我认为您的问题可能源于对 .onAppear 的误解。虽然您的代码将 onAppear 作为函数引用,但它通常是 modifier.

例如:

Text("When this text appears, it will call onAppear!")
    .onAppear {
        print("onAppear has been called... now what?")
    }

但是,如果您坚持使用 onAppear 函数,您可以直接从修饰符中调用它,如下所示:

Text("When this text appears, it will call onAppear()!")
    .onAppear {
        self.onAppear()
    }

现在,要更新您的class,就这么简单:

.onAppear {
    self.lastMeal.mealSize = 2000
    self.lastMeal.caloriesPerHour = 4000
    let someComplexCalculation = calculateCaloriesPerHour()
    print(someComplexCualculation)
    
}

很好,虽然这确实更新了输入值,并且由于 @Published 包装器而自动触发状态更改,但我们仍然没有提供一种方法来显示 someComplexCalculation 的结果视图。

这可以通过在视图中添加一个@State 变量来轻松实现,就在@ObservedObject 声明旁边:

@State calculatedValue = "please enter in you data"

然后在您的视图中显示:

VStack {
    Text("Your calculated value is:")
    Text(self.calculatedValue)
}

不要忘记在前面提到的 onAppear 语句中设置它:

.onAppear {
    let someComplexCalculation = calculateCaloriesPerHour()
    self.calculatedValue = someComplexCalculation
}

备注

我注意到您正在初始化 calculateCaloriesPerHour:

中的新值
let meal = FastingCalculation()
let user = UserDetails()

这不会根据您从用户那里收到的数据计算结果,如果您想更改此设置,请尝试将函数移至 ContentView,并使其引用存储的值:

 struct ContentView: View {
     func calculateCaloriesPerHour() -> Int {
        let meal = self.lastMeal
        let user = self.userInfo
        let cPH = user.dailycalories/meal.mealSize
        return cPH
     }

编码愉快!如果您是 Swift 和 SwiftUI 的新手,我强烈建议您查看我好朋友的 100 天教程† Paul:

Tutorial that helped me

† 我不隶属于 Paul。