Here is another answer for you. You have to implement the UITextFieldDelegate
and set the textField
delegate as self
. Then implement the below delegate method.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text, let textRange = Range(range, in: text) else {
return false
}
var updatedText = text.replacingCharacters(in: textRange, with: string)
updatedText.removeAll(where: {$0 == ":"})
let finalLength = updatedText.count + updatedText.count/2 - 1
if finalLength > 17 {
return false
}
for i in stride(from: 2, to: finalLength, by: 3) {
let index = updatedText.index(updatedText.startIndex, offsetBy: i)
updatedText.insert(":", at: index)
}
textField.text = updatedText
return false
}
The logic here is really easy to understand:
- Strip the string of all the ":" which you may have inserted last time.
- Insert the ":" at every 3rd position in the string and set the string manually in
shouldChangeCharacters
You should include other logic like character limit, character restrictions, copy-paste handling yourself. The answer just focusses on the logic involved in adding and removing “:”
You do not have to delete the ":" that is inserted when deleting characters. eg: If you have "45:D" and you press delete once, you will be left with "45" and not "45:".