i just coded this and it work fine for me.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var index = range.lowerBound
let fecha = textField.text!
if string == "" {
var array = Array(fecha)
array.remove(at: index)
if array.count > 2 {
if !array.contains("/"){
array.insert("/", at: 2)
}
}
textField.text = String(array)
let cursorPosition = textField.position(from: textField.beginningOfDocument, offset: index)!
textField.selectedTextRange = textField.textRange(from: cursorPosition, to: cursorPosition)
}else{
let expiracion = fecha.replacingOccurrences(of: "/", with: "")
if fecha != expiracion{
if index > 1 {
index = range.lowerBound - 1
}
}
var array = Array(expiracion)
if array.count < 4 {
print("index: \(index) - \(array)")
let newChar = Character(string)
array.insert(newChar, at: index)
print("new array: ", array)
if array.count > 2 {
array.insert("/", at: 2)
}
textField.text = String(array)
index = index > 1 ? index + 2 : index + 1
let cursorPosition = textField.position(from: textField.beginningOfDocument, offset: index)!
textField.selectedTextRange = textField.textRange(from: cursorPosition, to: cursorPosition)
}
}
return false
}