Created
December 21, 2020 11:23
-
-
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
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
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