- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to go through all text fields with the "Next" Button on the iPhone/iOS Keyboard?
To go through all the text fields one by one on tap on done or return button, we’ll have to create a logic. Let’s understand it with help of a project.
Create a project and on the view controller story board drag Four text fields.
Select them one by one and from attribute, inspector set their tags as 1,2,3,4 respectively.
Also set their return key to Done from the attribute inspector itself.
Create outlets for all four text fields in the View controller class, connect them to their respective outlets.
@IBOutlet weak var tf1: UITextField! @IBOutlet weak var tf2: UITextField! @IBOutlet weak var tf3: UITextField! @IBOutlet weak var tf4: UITextField!
Extend the ViewController class to UITextFieldDelegate, and write the method, textFieldShouldReturn
extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { } }
In the viewDidLoad() method of ViewController class, set their delegate to self, One by one.
override func viewDidLoad() { super.viewDidLoad() self.tf1.delegate = self self.tf2.delegate = self self.tf3.delegate = self self.tf4.delegate = self }
Now in the method, we wrote above, add the following lines of code
let nextTag = textField.tag + 1 let nextTF = textField.superview?.viewWithTag(nextTag) as UIResponder! if nextTF != nil { nextTF?.becomeFirstResponder() } else { textField.resignFirstResponder() } return false
The complete ViewController class should now look like this,
import UIKit class ViewController: UIViewController { @IBOutlet weak var tf1: UITextField! @IBOutlet weak var tf2: UITextField! @IBOutlet weak var tf3: UITextField! @IBOutlet weak var tf4: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.tf1.delegate = self self.tf2.delegate = self self.tf3.delegate = self self.tf4.delegate = self } } extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTag = textField.tag + 1 let nextTF = textField.superview?.viewWithTag(nextTag) as UIResponder! if nextTF != nil { nextTF?.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } }
This is how the app looks on xcode and simulator respectively