amayers/NumericText
TextField replacement for SwiftUI that restricts input to numbers
Usage:
NumericTextField
It works just like TextField but you are binding it to NSNumber? instead of a String.
// Inside your view
@State private var int: NSNumber?
@State private var double: NSNumber?
var body: Some View {
VStack {
NumericTextField("Int", number: $int, isDecimalAllowed: false)
NumericTextField("Double", number: $double, isDecimalAllowed: true)
}
}
NumericTextModifier
// Inside your view
@State private var int: NSNumber?
@State private var intString = ""
@State private var double: NSNumber?
@State private var doubleString = ""
var body: Some View {
VStack {
TextField("Int", text: $intString)
.numericText(text: $intString, number: $int, isDecimalAllowed: false)
TextField("Double", text: $doubleString)
.numericText(text: $doubleString, number: $double, isDecimalAllowed: true)
}
}
Installation
Use Swift Package Manager or just drag and drop the two source files into your project. It supports iOS 14, macOS 10.16/11, tvOS 14, watchOS 7.
Improvement ideas
- Ditch
NSNumber?as the bound value, and allow binding eitherInt?orDouble?. I took a quick shot at this, but my generics skills weren't sufficient to figure it out. - Support the other initializers that
TextFieldsupports.
Pull requests are welcome to help with these or any other things you may find or think of.
Package Metadata
Repository: amayers/NumericText
Stars: 20
Forks: 3
Open issues: 0
Default branch: main
Primary language: swift
License: MIT
README: README.md