Use BindingInt with a TextField SwiftUI
Actually , you can binding manyTypes with TextField
:
@State var weight: Int = 0
var body: some View {
Group{
Text("\(weight)")
TextField("Weight", value: $weight, formatter: NumberFormatter())
}}
SwiftUI TextField does not accept integers/double. How to do so?
SwiftUI’s components expect to have two-way bindings to properties, using something like @State, Have you used @State before declaring the num1 property ?
you can do something like this :
Declare the variable num1 as
@State private var num1 = ""
You TextField cant directly take Integer or Double input, you have to take only String input and can Typecast the required value during evaluation, as
print("Input taken is : \(Double(num1))")
Optional chaining the binding value in SwiftUI textfield
When use the "dot chaining" syntax on a Binding
its a shortcut syntax for creating a Binding
. It doesn't have the same semantics "lookup a property of this thing" that the dot syntax usually holds.
So $food.name
is not going to resolve the binding of food
then reference one of its properties. It going to create a two-way Binding<String>
to the name
property of the food.
Similarly, when you have $food.macroProfile
the value of that expression is a Binding<MacroNutrientProfile?>
... a binding that will directly change a value in food
(and the value it can change is an optional). It is not a resolution of the binding $food
followed by referencing one of that object's properties.
$food.macroProfile?.carb
is nonsensical because $food.macroProfile
is of type Binding<MacroNutrientProfile?>
which is not an optional type. So you see errors.
$food.name
is not nonsensical because it is a Binding<String>
and you're not trying to treat a non-optional value as an optional.
One way to change it is to use a custom binding:
struct Food: Codable, Identifiable {
var id = UUID()
var name: String = ""
var energy: Float?
var water: Float?
var macroProfile: MacronutrientProfile?
}
struct MacronutrientProfile: Codable {
var carb: Float?
var protein: Float?
var fat: Float?
}
struct SomeView : View {
@State var food: Food
let gram = NumberFormatter()
var body : some View {
let carbBinding = Binding<Float?>(get: { food.macroProfile?.carb },
set: { newValue in food.macroProfile?.carb = newValue })
return HStack {
Text("Carbohydrates")
Spacer()
TextField("Grams", value: carbBinding, formatter: gram)
.multilineTextAlignment(.trailing)
.keyboardType(.numberPad)
}
}
}
How to bind an observable objects published integer variable to a textField in SwiftUI?
Make it non-optional and remove the $
before $objectHeight
. Only leave the ViewModel one
$sharedViewModel.objectHeight
Recognize changes in SwiftUI TextField with double value
On iOS 15 you can use TextField ("Hello", value: $someDoubleValue, formatter: <your NumberFormatter here>)
and the value propagates fine.
On iOS 14, it doesn't seem to work binding a TextField
to a Double
value with a formatter.
So the following works fine in iOS 15, but does not work in iOS 14.
Note The double value is nested here because this is a code snippet taken from what I'm working on right now.
public class MyViewModel: ObservableObject {
@Published var child: ChildObject
}
public class ChildObject: Identifiable, ObservableObject {
@Published var doubleValue: Double
}
public struct FancyPantsView: View {
@ObservedObject var viewModel: MyViewModel
public var body: some View {
VStack {
TextField ("Hello", value: $viewModel.child.doubleValue, formatter: amountFormatter)
.keyboardType(.decimalPad)
}
}
let amountFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.zeroSymbol = ""
return formatter
}()
}
Formatting a BindingString that's within my TextField
I ended up utilizing https://github.com/marmelroy/PhoneNumberKit to get this to work. I used this gist https://gist.github.com/jbnunn/dab656b53f6e4ee2f53730f0b8daee64 to integrate it with SwiftUI.
Related Topics
How to Add Type Constraints to a Swift Protocol Conformance Extension
Send Data from Tableview to Detailview Swift
Unexpected Non-Void Return Value in Void Function (Swift 2.0)
How to Create Array of Unique Object List in Swift
Swift 2 - Pattern Matching in "If"
Get a Swift Variable'S Actual Name as String
Print Without Newline in Swift
Number of Words in a Swift String For Word Count Calculation
Swift Structs to Nsdata and Back
Share Data Between Main App and Widget in Swiftui For iOS 14
What Is the In-Practice Difference Between Generic and Protocol-Typed Function Parameters
Multiple Functions With the Same Name
How to Encode Enum Using Nscoder in Swift
Get Terminal Output After a Command Swift
Unwrapping Multiple Optionals in If Statement