I am developing an application where I am creating some UITextField
programmatically, and I allow a maximum 1 character in the UITextField
.
This is working perfectly.
But after writing the character, the user has to again tap in the next UITextField
to present the keyboard
After typing 1 character the cursor should automatically move to next UITextField
.
How can I do that?
If you're in a situation where your iOS app has multiple UITextField instances lined up, users expect to be able to move between them by pressing Next/Return on their on-screen keyboard.
func textFieldDidEndEditing(UITextField) Tells the delegate when editing stops for the specified text field.
Catch the delegate that informs you your textfield has been changed. Check if the new length is 1. If it is, call becomeFirstResponder
on the next field.
I have found this approach..
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(textField == textField1)
{
if (textField1.text.length > 0 && range.length == 0 )
{
return NO;
}
else {
[textField1 setText:newString];
[textField2 becomeFirstResponder];
return YES;
}
}
else if(textField == textField2)
{
if (textField2.text.length > 0 && range.length == 0 )
{
return NO;
}else {
[textField2 setText:newString];
[textField3 becomeFirstResponder];
return YES;
}
}
}
We can do it in another way... Declare this line in viewDidLoad and that method.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditingTextField:) name:@"UITextFieldTextDidChangeNotification" object:txtfield1];
- (void) endEditingTextField:(NSNotification *)note {
if ([[txtfield1 text] length] > 0)
{
[txtfield1 resignFirstResponder];
[txtfield2 becomeFirstResponder];
}
}
Hope this helps...
Above solution did not work. This solution does work for me:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(firstCodeField == textField){
[firstCodeField setText:newString];
[secondCodeField becomeFirstResponder];
}
if(secondCodeField == textField){
[secondCodeField setText:newString];
[thirdCodeField becomeFirstResponder];
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 1) ? NO : YES;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With