Handling non-ascii characters in textField:shouldChangeCharactersInRange:replacementString:

前端 未结 1 840
生来不讨喜
生来不讨喜 2021-01-14 21:11

I\'m trying to prevent Chinese (or otherwise, all non-ascii characters) from being input into a UITextField. As seen in other posts, I implemented textField:shouldChan

相关标签:
1条回答
  • 2021-01-14 21:53

    A workaround you can take is to use:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    

    then in your function:

    - (void)textChanged:(NSNotification *)notification{
      //remove observer
      [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
    
      //change your textfield's value here e.g.
      myTextField.text = [MyUtils removeNonAsciiChar:myTextField.text];
    
      //add observer again
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    

    Note however that this is more costly since you will be replacing the entire string everytime, but it should be okay if you're not expecting a very long string.

    0 讨论(0)
提交回复
热议问题