Skip to content

Instantly share code, notes, and snippets.

@grosch
Created December 21, 2020 11:23
Show Gist options
  • Save grosch/b41f9a0a2be00f47c62f99e82936860e to your computer and use it in GitHub Desktop.
Save grosch/b41f9a0a2be00f47c62f99e82936860e to your computer and use it in GitHub Desktop.
SwiftUI TextField which only accepts integers and binds to an Int? instead of a String
import SwiftUI
private class IntegerTextFieldValue: ObservableObject {
@Published var value = "" {
didSet {
let numbersOnly = value.filter { $0.isNumber }
if value != numbersOnly {
value = numbersOnly
}
}
}
}
struct IntegerTextField: View {
@Binding var value: Int?
@StateObject private var fieldValue = IntegerTextFieldValue()
var placeholder = ""
var body: some View {
TextField(placeholder, text: $fieldValue.value)
.keyboardType(.numberPad)
.onChange(of: fieldValue.value) { value = Int($0) }
.onAppear {
if let value = value {
fieldValue.value = "\(value)"
}
}
}
}
struct NumericTextField_Previews: PreviewProvider {
static var previews: some View {
IntegerTextField(value: .constant(17))
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment