0

What I am trying to do here is to pass the "KarvonenVal" to different View in another SwiftUI file. I have tried with .environmentObject and observableObject, but none of them worked. My goal is to display KarvonenVal on SummaryView. I appreciate your helps.

Value from

struct CalcProcess: View{
    @Binding var NumAdded3:Bool
    @State var Age:Int
    @State var ExerciseIT:Int
    @State var ConstantNumber = 220
    @State var RHR:Int
    
    func karvonen(cn: Int, rhr: Int, age: Int, ei:Double) -> Double {
        return Double((cn-age-rhr)) * (ei / 10) + Double(rhr)
    }
    
    var body: some View {
        let output = karvonen(cn: ConstantNumber, rhr: RHR, age: Age, ei: Double(ExerciseIT))
        let roundedDouble = Double(round(1000*output)/1000)
        let KarvonenVal: String = String(format: "%.1f", roundedDouble)
           
        VStack{
            Text("\(KarvonenVal)")
                .foregroundStyle(.red)
        }
    }
}

To Here

struct SummaryView: View {
    @EnvironmentObject var workoutManager: WorkoutManager
    @Environment(\.dismiss) var dismiss

    var body: some View {
            ScrollView {
                VStack(alignment: .leading) {
                    SummaryMetricView(title: "Total Time",
                                      value: durationFormatter.string(from: workoutManager.workout?.duration ?? 0.0) ?? "")
                        .foregroundStyle(.yellow)
                    SummaryMetricView(title: "Avg. Heart Rate",
                                      value: workoutManager.averageHeartRate.formatted(.number.precision(.fractionLength(0))) + " bpm")
                        .foregroundStyle(.red)
                    SummaryMetricView(title: "Target Heart Rate",
                                      value: KarvonenVal + " bpm")
                        .foregroundStyle(.red)
                    Button("Done") {
                        dismiss()
                    }
                }
                .scenePadding()
            }
            .navigationTitle("Summary")
            .navigationBarTitleDisplayMode(.inline)
    }
}
Epicminetime
  • 183
  • 1
  • 1
  • 6

1 Answers1

0

If the views are not directly related to each other so the Parameter Way or Binding Way is impossible you need a common class which both views have access to.

In your case in CalcProcess declare also

@EnvironmentObject var workoutManager: WorkoutManager

and pass the value – by the way even in SwiftUi variable names should start with a lowercase letter – to the workout manager.

However this requires that workoutManager is injected into the environment on a higher level where SummaryView is also a descendant of.

vadian
  • 274,689
  • 30
  • 353
  • 361