You can use the textField function shouldChangeCharactersIn range. To do this, you need to connect the UITextField delegate to your ViewController (either through the storyboard or through code), create an outlet for this textField in your ViewController code, implement the UITextFieldDelegate protocol, and use the code as described below. It will allow you to format for the Brazilian number already including the fifth number after the area code. To make it clear, below where I use "cellPhoneTextField", you should use the textField's outlet name for the phone number you have connected to 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
}
}