Xavi Valero
Xavi Valero

Reputation: 2057

Keypressed event in UITextField

I have 10 textfields, in which I could enter only one character in each textfield. After a character is entered in each textfield, the focus should move to the next one. Similarly when i delete character from a textfield by pressing the backspace or delete, i need to get the focus to the previous textfield. If I could get the keypressed event, I could do that. Right now I am not able to find any keypressed event examples.

Upvotes: 3

Views: 8648

Answers (5)

mAc
mAc

Reputation: 2514

You have to use the textfieldDelegate methods.

In your textFieldShouldReturn method you have to set your responders like

if (textfield == textField1)
{
    [textField2 becomeFirstResponder];
}
else if (textField == textField2)
{
    [textField3 becomeFirstResponder];
}
else
{
    [textField3 resignFirstResponder];
}

return YES; // as method return type is BOOL.

Upvotes: 0

visnup
visnup

Reputation: 499

Based on Aadhira's answer, but taking into account Kirk Woll's comment, you can generate what the latest text will be by using stringByReplacingCharactersInRange:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  NSString *value = [textField.text stringByReplacingCharactersInRange:range withString:string];
  NSLog(@"value: %@", value);
  return YES;
}

Upvotes: 4

Gopesh Gupta
Gopesh Gupta

Reputation: 707

you have to implement the UITextFieldDelegate protocol into your code and this method will tell you when you start begin editing in text field

– textFieldShouldBeginEditing:

and you can set the if condition in this method according to your requirement...

Upvotes: 0

Sergey Lost
Sergey Lost

Reputation: 2551

Just to give you directions:

  1. Assign tag to each text field.
  2. Implement UITextFieldDelegate. There are all the methods you need to detect any event that takes place inside the text field. In each method you can check the tag and move focus properly.

Hint: you can use [mainView viewWithTag:XX] to quickly pick the text field you need.

Each time the text is changed you can check the text property of the text field and it will give you the answer which button was pressed.

Upvotes: 0

Ilanchezhian
Ilanchezhian

Reputation: 17478

Implement UITextFieldDelegate.

Implement the delegate methods in the protocol. You can achieve the things you wanted.

You can set the focus by using the method becomeFirstResponder to the required textfield.

Have a look at the delegate method

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

The text field calls this method whenever the user types a new character in the text field or deletes an existing character.

So that could solve your problem.

Upvotes: 8

Related Questions