Skip to content

Instantly share code, notes, and snippets.

@yuraist
Created July 10, 2019 08:21
Show Gist options
  • Save yuraist/076e1ab9850c390b75661ababbe1ff15 to your computer and use it in GitHub Desktop.
Save yuraist/076e1ab9850c390b75661ababbe1ff15 to your computer and use it in GitHub Desktop.
UITextField Phone Number Format
import UIKit
extension UITextField {
func handlePhoneNumberField(withReplacingString string: String, in range: NSRange) {
let textFieldString = text! as NSString
var newString = textFieldString.replacingCharacters(in: range, with: string)
let validationSet = CharacterSet.decimalDigits.inverted
let numberArray = newString.components(separatedBy: validationSet)
newString = numberArray.joined()
if newString.count > 11 {
return
}
if newString.count > 0 {
if newString.first == "7" {
newString.insert("+", at: newString.startIndex)
} else if newString.first != "8" {
newString.insert("7", at: newString.startIndex)
newString.insert("+", at: newString.startIndex)
} else {
newString.remove(at: newString.startIndex)
newString.insert("7", at: newString.startIndex)
newString.insert("+", at: newString.startIndex)
}
}
if newString.count > 2 {
let newIndex = newString.index(newString.startIndex, offsetBy: 2)
let newIndexPlus = newString.index(newString.startIndex, offsetBy: 3)
newString.insert(" ", at: newIndex)
newString.insert("(", at: newIndexPlus)
}
if newString.count > 7 {
let newIndex = newString.index(newString.startIndex, offsetBy: 7)
let newIndexPlus = newString.index(newString.startIndex, offsetBy: 8)
newString.insert(")", at: newIndex)
newString.insert(" ", at: newIndexPlus)
}
if newString.count > 12 {
let newIndex = newString.index(newString.startIndex, offsetBy: 12)
newString.insert("-", at: newIndex)
}
if newString.count > 15 {
let newIndex = newString.index(newString.startIndex, offsetBy: 15)
newString.insert("-", at: newIndex)
}
text = newString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment