Search code examples
iphoneiosipadios5ios6

Backspace functionality in iOS 6 & iOS 5 for UITextfield with 'secure' attribute


I have a UITextfield for entering password with SECURE attribute enabled.

When the user taps outside the UITextfield after inputting a certain number of characters, and then taps back again to the UITextfield for editing, the following behavior is taking place:

iOS 5.1 -When I try to delete a character(using backspace from keyboard) from the UITextfield, the last character is deleted.

iOS 6.0 -When I try to delete a character from the UITextfield, all typed characters are getting deleted.

Am I doing something wrong, or is this a bug in iOS 6?


Solution

  • This is the intended behaviour under iOS6 and you shouldn't probably change it.

    If for whatever reason you really need this, you can override UITextField's delegate method textField:shouldChangeCharactersInRange:replacementString: and restore the old behaviour:

    #import "ViewController.h"
    
    @interface ViewController () <UITextFieldDelegate>
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.passwordField.delegate = self;
    }
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        if (range.location > 0 && range.length == 1 && string.length == 0)
        {
            // iOS is trying to delete the entire string
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
            return NO;
        }
        return YES;
    }
    
    @end