0

I am trying to restrict a UITextField's input to only alphanumeric characters ie. letters and numbers. I found a BOOL method implementation here on stack overflow: https://stackoverflow.com/a/16147160/3344977

So here is what I did with my code after reading that answer:

  1. I added this property to my main file's header:

    @property (nonatomic, strong) NSCharacterSet *charactersToBlock;
    
  2. Added this to my viewDidLoad:

    self.charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    
  3. Added the method implementation:

    - (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
    {
    
    return ([characters rangeOfCharacterFromSet:self.charactersToBlock].location == NSNotFound);
    
    }
    

And then I have tried calling the BOOL method in my viewDidLoad by starting to type this (_emailEntry is a UITextField property I have created in my view controller's header file):

[_emailEntry should

But xcode doesn't even show the option for our method of shouldChangeCharactersInRange which makes me think that I might be calling the BOOL method incorrectly.

I am not sure how to implement this correctly. Thanks for the help.

Community
  • 1
  • 1
user3344977
  • 3,454
  • 4
  • 29
  • 82
  • Check out this method http://stackoverflow.com/a/7010676/2526115 this method gets called BEFOREthe text field changed. shouldChangeCharactersInRange gets called AFTER the text field changes. – Ivan Lesko Mar 08 '14 at 04:48
  • The method (if you were going to call it directly, which you obviously don't) is not `[_emailEntry should...]`, but rather `[self textField:_emailEntry should...].` That's why you're not getting a hit on it. But you obviously just set the text field's delegate to be the view controller and iOS will call that method for you as users enter values into that field. You never invoke it directly yourself. – Rob Mar 08 '14 at 04:53
  • Thanks for clearing that up Rob. – user3344977 Mar 08 '14 at 04:56

1 Answers1

1

I just realized that there is no need to call the BOOL method. All you have to do is add the method implementation code to your view controller and you're good to go.

user3344977
  • 3,454
  • 4
  • 29
  • 82
  • Yes it is part of the UITextFieldDelegate protocol which you have no doubt implemented. The text field (assuming this class you're talking about is set to its delegate) will ask at appropriate times, ie when the user tries to edit character in range... – Jef Mar 08 '14 at 10:58