I\'m formatting my textfiled text once the user start typing the phone number into this format type 0 (555) 444 66 77
and it is working fine but once I get the
If you rather to do it without using a library. Here is a link to the best example or you can use the code below.
https://ivrodriguez.com/format-phone-numbers-in-swift/
A simple code snippet to format 10 digit phone numbers in Swift 5.0, instead of including a big library, just implement a delegate function and a formatting function:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var fullString = textField.text ?? ""
fullString.append(string)
if range.length == 1 {
textField.text = format(phoneNumber: fullString, shouldRemoveLastDigit: true)
} else {
textField.text = format(phoneNumber: fullString)
}
return false
}
func format(phoneNumber: String, shouldRemoveLastDigit: Bool = false) -> String {
guard !phoneNumber.isEmpty else { return "" }
guard let regex = try? NSRegularExpression(pattern: "[\\s-\\(\\)]", options: .caseInsensitive) else { return "" }
let r = NSString(string: phoneNumber).range(of: phoneNumber)
var number = regex.stringByReplacingMatches(in: phoneNumber, options: .init(rawValue: 0), range: r, withTemplate: "")
if number.count > 10 {
let tenthDigitIndex = number.index(number.startIndex, offsetBy: 10)
number = String(number[number.startIndex..