Created
November 22, 2016 17:27
-
-
Save Quaggie/8992fceff8e611a7c6b03e39d691ef20 to your computer and use it in GitHub Desktop.
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
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
if textField == cellPhoneTextField { | |
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) | |
let components = (newString as NSString).components(separatedBy: NSCharacterSet.decimalDigits.inverted) | |
let decimalString = components.joined(separator: "") as NSString | |
let length = decimalString.length | |
if length == 0 || length > 11 { | |
let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int | |
return (newLength > 11) ? false : true | |
} | |
var index = 0 as Int | |
var formattedString = "" | |
if (length - index) > 2 { | |
let areaCode = decimalString.substring(with: NSMakeRange(index, 2)) | |
formattedString.append("(\(areaCode))") | |
index += 2 | |
} | |
if length == 10 { | |
if length - index > 4 { | |
let prefix = decimalString.substring(with: NSMakeRange(index, 4)) | |
formattedString.append("\(prefix)-") | |
index += 4 | |
} | |
} else if length == 11 { | |
if length - index > 5 { | |
let prefix = decimalString.substring(with: NSMakeRange(index, 5)) | |
formattedString.append("\(prefix)-") | |
index += 5 | |
} | |
} | |
let remainder = decimalString.substring(from: index) | |
formattedString.append(remainder) | |
textField.text = formattedString | |
return false | |
} else { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment