Chisx
Chisx

Reputation: 1986

How to force the user to stop typing in UITextField but allow backspacing

I have a UITextField that my user uses to type out tags. I need to be able to at a very specific time - stop my user from continuing to type in the keyboard that is presented by default with UITextFields. However, I need my user to still be allowed to hit the backspace button on the iOS keyboard so that they can try and type a word that will fit.

A couple VERY important things to keep in mind:

  1. The UITextField should not be frozen due to a maximum amount of characters, because I am determining when the textField should be frozen based off of UIViews that I am adding to the screen for the tags
  2. The user still should be able to backspace
  3. The keyboard should not be dismissed
  4. The textField should not be disabled

I have tried setting the textField.enabled = NO, but once again, I need to still be able to use the textField, I just simply need to freeze the typing and force the user to backspace, not allowing andy characters to be added to the textField.

Upvotes: 1

Views: 536

Answers (3)

Suhail kalathil
Suhail kalathil

Reputation: 2693

Try this

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Prevent crashing undo bug – see note below.
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }

    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    if(textField == self.yourTextField)
    {
        return newLength <= CHARACTER_LIMIT;
    }
    else
    {
        return YES;
    }
}

Upvotes: 1

Smile
Smile

Reputation: 637

Try this, Back space will work even if the textfield pre populated with more than MAX_Length text

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
replacementString: (NSString*) string {
  NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string];

NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string];
if([text length] > MAX_LENGTH && string.length>0)
    return NO;
else
    return YES;
}

Upvotes: 0

Suresh Kumar Durairaj
Suresh Kumar Durairaj

Reputation: 2126

You could try something like below

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
replacementString: (NSString*) string {

  NSString *text = [textField.text stringByReplacingCharactersInRange:range withString: string];

  if([text length] > MAX_LENGTH)
       return NO;
  else 
       return YES;

 }

EDIT1: To this delegate method get called, set the textfield's delegate. In this case, you can use it as

yourTextField.delegate = self;

In your viewWillAppear/viewDidAppear.

Upvotes: 3

Related Questions