首页 > 解决方案 > 我想根据函数输出更新类中的信息。我希望这发生。onAppear

问题描述

当屏幕出现并返回 func calculateCaloriesPerHour 时,我想更新变量caloriesPerHour。

我为 .onAppear 代码留了一个空间(我假设那是代码应该去的地方?)

感谢您的帮助。

import Combine
import SwiftUI

这是我要更新的课程:

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)
            }
            
        }
    }
}

标签: swiftuiwatchos

解决方案


我认为您的问题可能源于对.onAppear. 虽然您的代码onAppear作为函数引用,但它通常是一个修饰符

例如:

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()
    }

现在,要更新您的课程,同样简单:

.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,我强烈建议您查看我的好朋友 † Paul 的 100 天教程:

对我有帮助的教程

† 我与保罗没有任何关系。


推荐阅读