Backspace functionality in iOS 6 & iOS 5 for UITex

2019-04-13 00:40发布

问题:

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?

回答1:

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


回答2:

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



回答3:

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!



回答4:

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?