Created
July 10, 2019 08:21
-
-
Save yuraist/076e1ab9850c390b75661ababbe1ff15 to your computer and use it in GitHub Desktop.
UITextField Phone Number Format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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