Я использую этот формат X (XXX) XXX XX XX это работа в Турции,
Я использую его с TableView с Swift 4
func formatToPhoneNumber(withPhoneTextField: UITextField, tableTextField: UITextField, range: NSRange, string: String) -> Bool {
if (tableTextField == withPhoneTextField) {
let newString = (tableTextField.text! as NSString).replacingCharacters(in: range, with: string)
let components = newString.components(separatedBy: NSCharacterSet.decimalDigits.inverted)
let decimalString = components.joined(separator: "") as NSString
let length = decimalString.length
let hasLeadingOne = length > 0 && decimalString.character(at: 0) == (1 as unichar)
if length == 0 || (length > 11 && !hasLeadingOne) || length > 12 {
let newLength = (tableTextField.text! as NSString).length + (string as NSString).length - range.length as Int
return (newLength > 11) ? false : true
}
var index = 0 as Int
let formattedString = NSMutableString()
if hasLeadingOne {
formattedString.append("1 ")
index += 1
}
if (length - index) > 1{
let zeroNumber = decimalString.substring(with: NSMakeRange(index, 1))
formattedString.appendFormat("%@ ", zeroNumber)
index += 1
}
if (length - index) > 3 {
let areaCode = decimalString.substring(with: NSMakeRange(index, 3))
formattedString.appendFormat("(%@) ", areaCode)
index += 3
}
if length - index > 3 {
let prefix = decimalString.substring(with: NSMakeRange(index, 3))
formattedString.appendFormat("%@ ", prefix)
index += 3
}
if (length - index) > 3{
let prefix = decimalString.substring(with: NSMakeRange(index, 2))
formattedString.appendFormat("%@ ", prefix)
index += 2
}
let remainder = decimalString.substring(from: index)
formattedString.append(remainder)
tableTextField.text = formattedString as String
return false
} else {
return true
}
}
, и вы можете назвать эту функцию в
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, indexPath: IndexPath) -> Bool {
}
в любом indexPath, что ваше текстовое поле в нем
например, мое текстовое поле в indexPath номер 1, поэтому код будет
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String, indexPath: IndexPath) -> Bool {
if indexPath.row == 1 {
let phoneTextField = textField
return formatToPhoneNumber(withPhoneTextField: phoneTextField, tableTextField: textField, range: range, string: string)
}
}