I have a OTP Screen, where I have to enter the OTP in 4 digit password in 4 Diff TextFields, The scenario is like this :
- A max character limit for each textfield is 1 and when the user enters a character in textfield it should move to next TextField.
- When the user clicks on back space, it should take back to previous textfield inorder to make the changes.
I have managed the working up to 70% but back space works only when the user enters all the textField. I'm pasting out my code.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// This allows numeric text only, but also backspace for deletes
if (string.length > 0 && ![[NSScanner scannerWithString:string] scanInt:NULL])
return NO;
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
// This 'tabs' to next field when entering digits
if (newLength == 1) {
if (textField == _pin1)
{
[self performSelector:@selector(setNextResponder:) withObject:_pin2 afterDelay:0];
}
else if (textField ==_pin2)
{
[self performSelector:@selector(setNextResponder:) withObject:_pin3 afterDelay:0];
}
else if (textField == _pin3)
{
[self performSelector:@selector(setNextResponder:) withObject:_pin4 afterDelay:0];
}
}
//this goes to previous field as you backspace through them, so you don't have to tap into them individually
else if (oldLength > 0 && newLength == 0) {
if (textField ==_pin4)
{
[self performSelector:@selector(setNextResponder:) withObject:_pin3 afterDelay:0];
}
else if (textField == _pin3)
{
[self performSelector:@selector(setNextResponder:) withObject:_pin2 afterDelay:0];
}
else if (textField == _pin2)
{
[self performSelector:@selector(setNextResponder:) withObject:_pin1 afterDelay:0];
}
}
return newLength <= 1;
}
- (void)setNextResponder:(UITextField *)nextResponder
{
[nextResponder becomeFirstResponder];
}
working: