Hi! This is a simple UITextField sublass that handles formatting, input validation and cursor position for you!
Just put DGInputField folder into your project!
You can just make your textfield of DGInputField class in your storyboard or just create it programmatically
DGInputField takes delegation of UITextField that's why you should not override delegate property. Another delegate is provided:
public protocol DGInputFieldDelegate: UITextFieldDelegate {
func textDidChange(in textField: DGInputField, formattedText: String, unformattedText: String)
}If you do not specify formatter, then formattedText will be equal to unformattedText
To add formatting for your input you should implement StringFormatterProtocol :
public protocol StringFormatterProtocol {
func format(_ string: String) -> String
func removeFormat(_ string: String) -> String
}You can look an example in demo project. There is CardNumberFormatter to format input in groups of 4
For now validation is made to prevent incorrect input. Perhaps it will be reworked in future. Just like formatting to support validation you just implement protocol InputStringValidatorProtocol:
public protocol InputStringValidatorProtocol {
func isValid(string: String) -> Bool
}If you set both formatter and validator, format is removed before checking string validation.
To set DGInputField configuration use TextFieldConfiguration like in example:
let configuration = TextFieldConfiguration(
formatter: CardNumberFormatter(),
validator: CardNumberInputValidator())
creditCardField.setConfiguration(configuration)Thats it!
This repository's code is distributed under MIT license.
