Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Created August 2, 2021 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magnuskahr/6ee53d0536aa4dae0f1f0f450639b007 to your computer and use it in GitHub Desktop.
Save magnuskahr/6ee53d0536aa4dae0f1f0f450639b007 to your computer and use it in GitHub Desktop.
An integer field in swiftui
struct IntegerField: View {
@Binding var value: Int
@State private var stringValue: String
init(value binding: Binding<Int>) {
self._value = binding
self._stringValue = State(wrappedValue: binding.wrappedValue.formatted())
}
var body: some View {
TextField("", text: $stringValue, onCommit: commit)
.disableAutocorrection(true)
.keyboardType(.numberPad)
.submitLabel(.done)
.onSubmit(commit)
.onDisappear(perform: commit)
.onChange(of: stringValue) { _ in
commit()
}
}
private func commit() {
if stringValue.isEmpty {
stringValue = "0"
value = 0
return
}
guard let number = Int(stringValue) else {
stringValue = String(value)
return
}
value = number
stringValue = String(number)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment