'Using user input in SwiftUI to perform calculations
I'm making a school project in which I have to find the weight of a person on different planets, but I am confused about how I should use the input and multiply it by the gravity on each planet.
Also, I am not sure whether or not weight is an int and can be multiplied with another number.
Here is my code:
struct PlanetDetail: View {
let planet : Planet
@State var weight = ""
var body: some View {
VStack {
Text(planet.name)
Text("Gravity on mercury is\(planet.gravity)")
TextField( "Enter your weight", text:$weight)
Text("your weight on \(planet.name) is ")
}
}
}
Solution 1:[1]
You have specified your weight variable like this:
@State var weight = ""
By assigning an empty string (""
), you have declared weight to be a String.
In order to multiply this value with an integer, you will need to convert the string value to an integer.
You will also need handle the case where a user could enter non-numeric values into your text input.
Instead, store the weight value as an integer.
You can take care of this by creating a Binding that is used when the user enters a value into the text field. For example:
@State var weight = 0
var body: some View {
let weightProxy = Binding<String>(
get: { String(format: "%.02f", Int(self.weight)) },
set: {
if let value = NumberFormatter().number(from: $0) {
self.weight = value.intValue
}
}
)
You would then bind your TextField to weightProxy:
TextField( "Enter your weight", text:$weightProxy)
The best case scenario would be to have a TextField that only accepts numbers. That is a bit more work, but could be a good project to tackle next!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |