Hello, I come across a problem I cannot solve, also the stack overflow results don’t show the solution. I also searched this forum.
I have to Integer variables which are in a Textfield and want to make a mathematic addition and present it as a variable in a Text. But the Initialization does not work correctly
That’s what I want to achieve
var var1 = 1
var var2 = 2
var result = (var1 * 75) + (var2 * 85)
That’s my solution but it does not work unfortunately
Thanks for reading
import SwiftUI
class Crew {
var var1:Int = 1
var var2:Int = 2
var result:Int = (var1 * 75) + (var2 *85)
After looking at this more closely there’s several reasons why it wasn’t working:
Like I originally said, at first, you need to use the Published property wrapper
I changed result to be a computed property, because if you’re only going to use it as a “result” for something, and not actually have the user do anything with, it’s better for it to be computed
changing the initializer to not use State because you don’t need to
Also removed result from the initializer because I changed it to a computed property
Inside DOWView it should actually be using StateObject
For showing the result, you’re trying to use string interpolation, but you had the syntax wrong, it looks like: "whatever string you want \(variableName) more random words"
with this solution I guess it is not possible to pass the result variable (crew.result) in to another View ? Am I correct ? It gets stuck in this single View
class Crew: ObservableObject { @Published var var1:Int = 0 @Published var var2:Int = 0
var result:Int {
(var1 * 75) + (var2 * 85)
}
class DowWeights: ObservableObject {
let basicweight:Int = 35000 @Published var cockpit:Int = 0 @Published var cabin:Int = 0
var crew:Int { Int((cockpit * 85) + (cabin * 75)) }
var result:Int { basicweight + crew + pantry }
//wanted to rewrite this variable to @Published but it does not work
init(pantry:Int, cockpit: Int, cabin: Int) {
self.cockpit = cockpit
self.cabin = cabin
}
}
ParentView with Textfield:
struct DOWView: View {
@ObservedObject var dowweights = DowWeights(cockpit: 1, cabin: 1, potwater: 5)
var body: some View {
VStack {
Text(“(dowweights.basicweight)”)
TextField(“#”, value: $dowweights.cockpit, formatter: NumberFormatter())
TextField(“#”, value: $dowweights.cabin, formatter: NumberFormatter())
Text(“(dowweights.result)”) //Result of all together
}
ChildView:
struct FuelView: View {
@ObservedObject var resultcall = DowWeights( cockpit: 0, cabin: 0)
var body: some View {
Text("\resultcall.result)")
}
}
Rewrite the variable result to @Published does not work.
I am making an instance in my FuelView of the class DowWeights with the ObservedObject but the changes in resultcall.result don’t change when I type something in the Textfield of the ParentView (DOWView) and don’t update. I think because it is not stored somewhere. Maybe I have to use UserDefaults to save it somewhere ?