Created
August 2, 2021 18:54
-
-
Save magnuskahr/6ee53d0536aa4dae0f1f0f450639b007 to your computer and use it in GitHub Desktop.
An integer field in swiftui
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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