I have a simple scene (using storyboard in IB) with a Username and Password text box. I\'ve set the keyboard to close when you are on the Password text field but can\'t get
Many solutions to this problem exist. See the responses posted to this question: How to navigate through textfields (Next / Done Buttons).
Read more in the UIResponder Class Reference.
The swift version could be:
extension LoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.emailTextField {
passwordTextField.becomeFirstResponder()
} else if textField == self.passwordTextField {
passwordTextField.resignFirstResponder()
}
return true
}
}
I tried to use Esteve's answer but it doesn't work. Maybe because I'm using xib files. What I've done is change his code to make it works in my code.
It works in the same way. All you need is to assign the order value as tag, and return key according to Next or Done or Send on each input control.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
if(textField.returnKeyType==UIReturnKeyNext) {
UITextField *next = (UITextField *)[self.view viewWithTag:textField.tag+1];
[next becomeFirstResponder];
} else if (textField.returnKeyType==UIReturnKeySend) {
//Do whatever you want with the last TextField
}
return YES;
}
Here's what you would put:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == self.textPassword) {
[theTextField resignFirstResponder];
} else if (theTextField == self.usernameField) {
[self.textPassword becomeFirstResponder];
}
return YES;
}
for those who want to use Swift language:
class MyClass: UIViewController, UITextFieldDelegate {
@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!
@IBOutlet weak var text3: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
text1.delegate = self
text2.delegate = self
text3.delegate = self
}
//....
func textFieldShouldReturn(textField: UITextField) -> Bool{
if textField == self.text1 {
self.text2.becomeFirstResponder()
}else if textField == self.text2{
self.text3.becomeFirstResponder()
}else{
self.text1.becomeFirstResponder()
}
return true
}
//...
}
:-)