sguruapp@gmail.com
facebook vk instagram Телеграм youtube

TextField форматирование номера телефона (UITextField for Phone Number format) 1 вариант - Swift 5


@IBOutlet weak var phoneField: UITextField!
phoneField.delegate = self

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if (textField == phoneField) {
let newString = (textField.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.hasPrefix("7")

if length == 0 || (length > 10 && !hasLeadingOne) || length > 11 {
let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int

return (newLength > 10) ? false : true
}
var index = 0 as Int
let formattedString = NSMutableString()

if hasLeadingOne {
formattedString.append("+7 ")
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
}

let remainder = decimalString.substring(from: index)
formattedString.append(remainder)
textField.text = formattedString as String
return false
}
else {
return true
}
}

Возврат к списку

обучись профессии будущего

Хочешь стать успешным разработчиком
приложений? Тогда добро пожаловать к нам.

обучись профессии будущего