5 Replies
      Latest reply on Jan 12, 2019 4:39 PM by Joel14
      Joel14 Level 1 Level 1 (0 points)

        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.

        • Re: Format
          Claude31 Level 8 Level 8 (5,485 points)

          You can define it in IB:

          - select the textField

          - open its attribute inspector

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

          • Re: Format
            eskimo Apple Staff Apple Staff (10,605 points)

            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"