开发者

How to use PhoneNumberFormatter class to format phone number in UITextField?

开发者 https://www.devze.com 2023-03-31 02:33 出处:网络
I\'ve been looking at a bunch of the threads here about trying to autoformat a UITextField into a phone number. I saw the links to Ahmed Abdelkader\'s PhoneNumberFormatter class ( http://the-lost-beau

I've been looking at a bunch of the threads here about trying to autoformat a UITextField into a phone number. I saw the links to Ahmed Abdelkader's PhoneNumberFormatter class ( http://the-lost-beauty.blogspot.com/2010/01/auto-formatting-phone-number.html )

But I don't understand how to actually implement it. I've got two UITextFields that I want to use with the class, in a form with many other UITextFields for other purposes.

Ahmed's example is:

UITextField *myTextField;
int myTextFieldSemaphore;
PhoneNumberFormatter *myPhoneNumberFormatter;
NSString *myLocale; //@"us"

//init semaphore
myTextFieldSemaphore = 0;

//bind events
[myTextField addTarget:self
                action:@selector(autoFormatTextField:)
      forControlEvents:UIControlEventEditingChanged
];

//handle events
- (void)autoFormatTextField:(id)sender {
  if(myTextFieldSemaphore) return;
 myTextFieldSemaphore = 1;
 myTextField.text = [phoneNumberFormatter format:myTextField.text wi开发者_C百科thLocale:myLocale];
 myTextFieldSemaphore = 0;
}

I'm not really sure where to put the above code, or how to sub in my properties instead of his variables. So far I've only been able to get the textfields to refuse input :/ - Has anyone got an example of a more complete implementation of this class?


Just put this code in the class which implements UITextFieldDelegate. myTextField should be replaced with your UITextField instance. Instead of using myLocale, you should be fetching the device's current locale. And PhoneNumberFormatter can be allocated & released after use.

- (void)autoFormatTextField:(id)sender
{
     if(myTextFieldSemaphore) return;
         myTextFieldSemaphore = 1;

     PhoneNumberFormatter* phoneNumberFormatter = [[PhoneNumberFormatter alloc] init];
     myTextField.text = [phoneNumberFormatter format:myTextField.text withLocale:[[NSLocale currentLocale] localeIdentifier]];
     [phoneNumberFormatter release];
     myTextFieldSemaphore = 0;
}


Turns out I was able to hook it up in IB instead of using that bind statement. Works great! The only thing is that the currentLocale recommendation doesn't match with the assumptions in the class, so I had to edit the class to use en_US instead of us


you can also format phone number using google javascript "phoneutil" library. i done it its working fine. steps:

  1. add javascript libraries.
  2. create a webview.
  3. create one html file(include all the headers of phoneutil library).
  4. like a normal html file, create a

    // write you custom function here to get the formatted phone numbers .. .. ..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号