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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 15:18:55

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

There is also an issue with iOS 6 w/ regard to this new behavior. Try this:

  1. Navigate to a view with two UITextFields, one which is secure
  2. Type anything into the non-secure text field.
  3. Tap into the secure text field, do not type or delete anything. Tap back into the non-secure field
  4. Hit backspace once

Viola! You have nothing in your text field now. I am able to reproduce this consistently with iOS 6.0.x and 6.1

Looks like this can be fixed by explicitly setting secureTextEntry to NO in viewDidLoad or thereabouts.

- (void)viewDidLoad {
    [super viewDidLoad];

    self.textField.secureTextEntry = NO;
}

This seems to work with the case described above (a view with an email field and a secure password field on it), under iOS 6.

HTH!

crizzwald

Here is a way to detect if a secure field is going to be cleared by a backspace:

iOS 6 UITextField Secure - How to detect backspace clearing all characters?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!