You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A simple SwiftUI `TextField` that limits user input to numbers.
6
4
7
5
The most common response in https://stackoverflow.com/questions/58733003/swiftui-how-to-create-textfield-that-only-accepts-numbers (the top search result), advocates just setting a numeric keyboard. But that totally misses cases when used with hardware keyboards. Many of the suggested
8
6
9
-
This `NumericTextField` prevents any non-numeric text input, no matter the source (paste, external keyboard). You can choose to allow integers or floating point.
7
+
This `NumericTextModifier` observes a `String` value for changes, and when it is changed, it filters out any non-numeric characters and updates the string. Then it converts that string to a `NSNumber` for easier use. You can choose to allow integers or floating point.
8
+
9
+
`NumericTextField` uses `NumbericTextModifier` and exposes only the `NSNumber` in the text. It prevents any non-numeric text input, no matter the source (paste, external keyboard). It also manages the keyboard type to match the type of numbers you said to allow.
10
+
10
11
Standard `TextFields` have a `Formatter` that you can pass in, that will be used to format/validate input. However this only occurs when the user finishes editing, not for every keystroke. So a user can type `123abc4` and see that in the text field, then when they hit return it will change to `1234`. That's really not ideal. With `NumericTextField` when they type a non-numeric character it is ignored and never shows up in the text field.
11
12
12
13
13
14
## Usage:
14
15
16
+
### NumericTextField
17
+
15
18
It works just like `TextField` but you are binding it to `NSNumber?` instead of a `String`.
0 commit comments