我无法拦截Numpad的后退按钮

时间:2014-05-31 14:07:24

标签: ios objective-c uitextfield uitextfielddelegate

我希望firstResponder在按下后退或返回键时转到上一个TextField。但是textFieldShouldReturn没有启动。非常感谢你们!

尝试this,但它似乎无法正常工作。

MyViewController.h

@interface MyViewController : UIViewController <UITextFieldDelegate>

@property (strong, nonatomic) IBOutlet UITextField *firstCodeField;

MyViewController.m

@synthesize firstCodeField;

- (void)viewDidLoad
{
[super viewDidLoad];
firstCodeField.delegate = self;
secondCodeField.delegate = self;
thirdCodeField.delegate = self;
fourthCodeField.delegate = self;
fifthCodeField.delegate = self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    if (string.length == 0 && textField.text.length)
    {
        if(textField==fifthCodeField) {
            NSLog(@"It goes to fourth textfield but doesn't clear the number in the cell.");
            [textField resignFirstResponder];
            [fourthCodeField becomeFirstResponder];
            return NO;
        }
    }

    return (newLength > 1) ? NO : YES;
}

enter image description here

1 个答案:

答案 0 :(得分:0)

必须在textField :shouldChangeCharactersInRange:

中识别后退空间
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
      {
        if (string.length == 0 //BackSpace
            && textField.text.length)//No Characters in text field
        {
            [textField resignFirstResponder];
            return NO;
        }
        return YES;
    }

更新了答案。当第五个字段为空时,单击后退空格将移至第四个字段并清除第四个字段中的最后一个字符

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        NSUInteger newLength = [textField.text length] + [string length] - range.length;

        if (string.length == 0 && textField.text.length)
        {
            if(textField==fifthCodeField) {
                NSLog(@"It goes to fourth textfield but doesn't clear the number in the cell.");
                [textField resignFirstResponder];

                //Character range for last character
                NSRange fourthFieldRange;
                range.length = 1;
                range.location = field.text.length - 1;

                NSString *text = [fourthCodeField.text stringByReplacingCharactersInRange:fourthFieldRange withString:@""];
                 [fourthCodeField becomeFirstResponder];
                return NO;
            }
        }

        return (newLength > 1) ? NO : YES;
    }