I am having problems trying to get the keyboard to go to the next field or return when the return key is pressed, my code is:
@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UITextField *userField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (strong, nonatomic) UITextField *textField;
@end
@implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidLayoutSubviews
{
[self.userField becomeFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)tapLogin:(id)sender {
NSLog(@"login");
}
#pragma mark - UITextFieldDelegate methods
// for return and next
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
if (textField == self.userField) {
[self.passwordField becomeFirstResponder];
}
else if (textField == self.passwordField) {
[self tapLogin:nil];
}
return YES;
}
The cursor beings in the userField but hitting the return key does nothing, if I manually tap on another field i.e the password one this also won't do anything. The cursor is stuck in the username field. I have implemented the protocol in my header file and also set the text fields as delegates in the interface builder. Could someone help please?
Try this,
Remove [self.userField becomeFirstResponder];
method from viewDidLayoutSubviews
ie, remove the below method
- (void)viewDidLayoutSubviews
{
[self.userField becomeFirstResponder];
}
and add
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.userField becomeFirstResponder];
}