AJS AJS - 6 months ago 35
iOS Question

Follow up to phone formatting: More than 1 phone number field.

I have a question regarding the phone number formatting code in Swift 3 / Xcode. Vikzilla supplied excellent code for formatting. However, I have 2 phone fields in my app. One is phone number, the other is fax number. As mentioned, the answer supplied by Vikzilla is perfect but I can't for the life of me figure out what I need to edit in this code for the second field (fax number) without either throwing " invalid redeclaration of 'textfield..." error. I have renamed the 2nd function etc. no errors are thrown but the formatting of the fax field doesn't work... Help? Below is the code. As I mentioned it works perfect but I am not sure how to edit it so it will work on the 2nd. field (faxNumber). Thanks!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField == self.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.character(at: 0) == (1 as unichar)

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("1 ")
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)
textField.text = formattedString as String
return false
} else {
return true

Answer Source

You only need the one shouldChangeCharactersIn method. Simply remove the initial if (and its else). Then your code will work for both text fields.

If you actually have more than just the two phone number text fields then simply update the if to be:

if (textField == self.phoneField || textField == self.faxField) {

As a side note, your code will only work for phone numbers in the USA and Canada, not any other countries.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download