I was wondering how I can format the textField that I'm using for a phone number (ie like the "Add New Contact" page on the iPhone. When I enter in a new mobile phone, ex. 1236890987 it formats it as (123) 689-0987.) I already have the keyboard set as the number pad.
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- back button text does not change
相关文章
- 现在使用swift开发ios应用好还是swift?
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- How do you detect key up / key down events from a
Here is my solution.. works great! Formats the phone number in realtime. Note: This is for 10 digit phone numbers. And currently it auto formats it like (xxx) xxx-xxxx.. tweak to your hearts delight.
First in your
shouldChangeCharactersInRange
you want to gather the whole string for the phone text field and pass it to the validation/formatting function.And here is where the phone number is formatted. The regex could probably be cleaned up a bit. But I have tested this code for a while and seems to pass all bells. Notice we also use this function to delete a number in the phone number. Works a little easier here because we already stripped out all the other non digits.
Updated answer for Swift 2.0 from Vikzilla:
Worked excelente for me, hope it works for you too :)
You can use this library https://github.com/luximetr/AnyFormatKit
Example
Just set your textField to this textInputController and it will format text with pattern, that you set.
Or
for format full string
https://github.com/chebur/CHRTextFieldFormatter works for me like a charm.
Copy/paste from usage page:
Also swift:
This solution works great for North American numbers without the international dialing prefix (+1) and no extension. The number will be formatted as "(212) 555-1234". It will pre-type the ") " and the "-", but will also delete correctly.
Here is the
-textField:shouldChangeCharactersInRange:replacementString
that your text field delegate should implement:Below function enforces (999)333-5555 format on the textField:
Swift 3: