You can define it in IB:
- select the textField
- open its attribute inspector
- in text input traits, select phone number as content type.
That didn't do anything.
The only thing I am having a problem with is what should I put in the parameters when I implement the function:
(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String)
select phone number as content type
Setting the content type of the field doesn’t automagically reformat user input to look like a phone number, it just provides a text input hint for the system.
I want if some enter their phone number 3101231234 it to look like this (310)123-1234 how would I be able to accomplish this.
This is very tricky to do in the general case. Ideally you could piggyback off the work that Apple has done in this space, as reflected in the Contacts app, but I don’t think that’s possible right now. The Contacts framework has a formatter for names (
CNContactFormatter) and postal addresses (
CNPostalAddressFormatter), but not one for phone numbers.
If you’d like to see such support added in the future, I encourage you to file an enhancement request describing your requirements. Please post your bug number, just for the record.
In the meantime, I can see two ways forward here:
If you can constrain the problem, you could do your own phone number formatting. For example, if you’re only expecting to deal with NANPA-style phone numbers, it’s reasonable to write your own code for this.
If you can’t constrain the problem — that is, you have to accept and format any phone number — writing your own code for that is way too hard, and thus I recommend that you investigate using a third-party library.
ps It would help if you could set your thread titles to something more meaningful, like “Formatting phone numbers” rather than just “Format”.
Share and Enjoy
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"