Reputation: 11
I am a newbie in iOS programming, So i have 2 textFields and 1 button, I want the return key in textfield1 is next key and in the textfield2 is done key, when I press this button(the next key), the cursor will in textfield2, and when i press the done key in textfield2 it will performs the button. I cant handling the events, anyone can help me?
Upvotes: 0
Views: 253
Reputation: 2010
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
if (textField == self.textField1) {
[self.textField2 becomeFirstResponder];
} else {
[button sendActionsForControlEvents:UIControlEventTouchUpInside];
}
return YES;
}
Upvotes: 0
Reputation: 7343
You have to implement a UITextFieldDelegate
method for this, and set the delegates of the text fields to self
(self
being your UIViewCiontroller
):
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
if (textField == self.textField1) {
[self.textField2 becomeFirstResponder];
} else {
[self buttonTapped:self.button];
}
return YES;
}
As for what to see on your key, you can set it as the "Return Key" in the interface builder
Upvotes: 0
Reputation: 2745
Two textfields with Tags - 1 & 2
One IBAction method for textfields.
Bind method from your view's textfields. -> Did End On Exit Event
- (IBAction)returnAction:(id)sender
{
if ([sender tag] == 1) {
[textField2 becomeFirstResponder];
} else {
//YOUR_ACTION to perform;
}
}
You can also perform with Delegate method
-(BOOL)textFieldShouldReturn:(UITextField *)textField;
Thanks.
Upvotes: 0
Reputation: 7410
Let's consider you linked your textfields to your .h, creating 2 IBOutlet
s, and an outlet and an action for your button:
@property (weak, nonatomic) IBOutlet UITextField *firstField;
@property (weak, nonatomic) IBOutlet UITextField *secondField;
@property (weak, nonatomic) IBOutlet UIButton *button;
- (IBAction)buttonPress:(id)sender;
In your .m file, in the viewDidLoad
, add this:
_firstFieldField.delegate = self;
_secondField.delegate = self;
Back in your .h file, conform your class to the UITextFieldDelegate
protocol:
@interface MyViewController : UIViewController <UITextFieldDelegate>
Then, in your .m, you can implement the following method, which will be called when you press the "done" button on the keyboard:
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == _usernameField) {
_firstField becomeFirstResponder];
}
else if (textField == _passwordField) {
[_secondField resignFirstResponder];
[self buttonPress:_button];
}
return NO;
}
Upvotes: 1