You can use the function textField shouldChangeCharactersIn range. To do this, you need to connect the Uitextfield delegate to your Viewcontroller (either through storyboard or through code), create an outlet for that textField in your Viewcontroller code, implement the Uitextfielddelegate protocol, and use the code as described below. It will allow you to format the Brazilian number already including the fifth number after the area code. To make it clear, below where I use "cellPhoneTextField", you must use the name of the textField outlet for the phone number you have connected with the storyboard.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == cellPhoneTextField {
//New String and components
let newStr = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let components = (newStr as NSString).components(separatedBy: NSCharacterSet.decimalDigits.inverted)
//Decimal string, length and leading
let decimalString = components.joined(separator: "") as NSString
let length = decimalString.length
let hasLeadingOne = length > 0 && decimalString.character(at: 0) == (1 as unichar)
//Checking the length
if length == 0 || (length > 11 && !hasLeadingOne) || length > 13 {
let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int
return (newLength > 11) ? false : true
}
//Index and formatted string
var index = 0 as Int
let formattedString = NSMutableString()
//Check if it has leading
if hasLeadingOne {
formattedString.append("1 ")
index += 1
}
//Area Code
if (length - index) > 2 {
let areaCode = decimalString.substring(with: NSMakeRange(index, 2))
formattedString.appendFormat("%@ ", areaCode)
index += 2
}
if length - index > 5 {
let prefix = decimalString.substring(with: NSMakeRange(index, 5))
formattedString.appendFormat("%@-", prefix)
index += 5
}
let remainder = decimalString.substring(from: index)
formattedString.append(remainder)
textField.text = formattedString as String
return false
} else {
return true
}
}
Opa, using this your code is possible to adapt to something like: If the phone is 8 digits, the space stay after the 4th digit and if it is 9 stay after the 5th
– LMaker