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

青春壹個敷衍的年華 提交于 2019-12-11 01:25:43

问题


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 withLocale: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?


回答1:


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;
}

HTH,

Akshay




回答2:


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




回答3:


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 .. .. ..



来源:https://stackoverflow.com/questions/7184094/how-to-use-phonenumberformatter-class-to-format-phone-number-in-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!