Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format elements like Phone Number #54

Open
justdan0227 opened this issue Jul 14, 2021 · 3 comments
Open

Format elements like Phone Number #54

justdan0227 opened this issue Jul 14, 2021 · 3 comments

Comments

@justdan0227
Copy link

Is there a way to add formatting rules for fields like phone numbers to be (xxx) xxx-xxxx ?

@justdan0227
Copy link
Author

Can you capture the textfield delegate to so something like is posted in stackoverflow for phone number formatting?

/// mask example: +X (XXX) XXX-XXXX`
func format(with mask: String, phone: String) -> String {
let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
var result = ""
var index = numbers.startIndex // numbers iterator

// iterate over the mask characters until the iterator of numbers ends
for ch in mask where index < numbers.endIndex {
    if ch == "X" {
        // mask requires a number in this place, so take the next one
        result.append(numbers[index])

        // move numbers iterator to the next index
        index = numbers.index(after: index)

    } else {
        result.append(ch) // just append a mask character
    }
}
return result

}
Call the above function from the UITextField delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
let newString = (text as NSString).replacingCharacters(in: range, with: string)
textField.text = format(with: "+X (XXX) XXX-XXXX", phone: newString)
return false
}
So, that is work better.

"" => ""
"0" => "+0"
"412" => "+4 (12"
"12345678901" => "+1 (234) 567-8901"
"a1_b2-c3=d4 e5&f6|g7h8" => "+1 (234) 567-8"`

@neoneye
Copy link
Owner

neoneye commented Jul 14, 2021

I can't remember. I think it's difficult to do live-updates with the UIKit textfield as the user types in text. Phone numbers are tricky and localized. Maybe UIKit textfield already has support for phone number formatting.

Ideas to try out:

  • first make it work with the UIKit textfield as a standalone app.
  • next adapt the textfield code to a SwiftyFORM customcell.
  • Or modify the SwiftyFORM textfield in such way that it can do the formatting.

@justdan0227
Copy link
Author

@neoneye Thanks.. will try and report back

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants