Format

I wanted to know how would I format someone's text that is entered into a text field. For example, 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.

Replies

You can define it in IB:

- select the textField

- open its attribute inspector

- in text input traits, select phone number as content type.

Claude31 wrote:

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.

Joel14 wrote:

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"

That didn't do anything.

Exact. It may just adapt the keyboard, but not very useful.


Here is a link to a formatter, for US phone numbers only.

https://stackoverflow.com/questions/1246439/uitextfield-for-phone-number/39789375

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)