Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just to clarify: As a user enters a phone number into a UITextField, you would like it to automatically insert dashes in the proper places.</p> <p>The answer is in using the UITextFieldDelegate protocol. </p> <p>1) Set your controller object as a delegate for the UITextField.</p> <p>2) You'll find the following method in the protocol:</p> <pre><code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string </code></pre> <p>This method is called every time a character change occurs in the text field.</p> <p>3) How robust you want your implementation to be is up to you. You could simply do a count of the current characters and insert dashes after 3 and 6 characters. It would be wise to also reject any non-numeric characters.</p> <p>Here is a sample implementation. We basically take over the field editing manually - Inserting dashes after the appropriate string lengths and making sure the user can only enter numbers:</p> <pre><code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789-"]; NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; int charCount = [newString length]; if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound || [string rangeOfString:@"-"].location != NSNotFound || charCount &gt; 12) { return NO; } if (charCount == 3 || charCount == 7) { newString = [newString stringByAppendingString:@"-"]; } textField.text = newString; return NO; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload