Fred White Fred White - 4 years ago 200
iOS Question

Swift: textFieldShouldReturn not being called when using multiple textFields

is not being called when using more than one
. The
are set up as numpads and they should save the user input to the variable
, but
is not being called when the user taps of the

class TestViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var textFieldOne: UITextField!
@IBOutlet weak var textFieldTwo: UITextField!
@IBOutlet weak var textFieldThree: UITextField!
@IBOutlet weak var textFieldFour: UITextField!

var textFieldEntry: Int?

override func viewDidLoad() {
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

// does not recognise tap when inside view
tap.cancelsTouchesInView = false


self.textFieldOne.delegate = self
self.textFieldTwo.delegate = self
self.textFieldThree.delegate = self
self.textFieldFour.delegate = self

func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
var firstResponder = findActiveResponderFrame(view: view)

var testVar: Int?
if firstResponder!.tag == 0 {
testVar = Int(textFieldOne.text!)
} else if firstResponder!.tag == 1 {
testVar = Int(textFieldTwo.text!)
} else if firstResponder!.tag == 2 {
testVar = Int(textFieldThree.text!)
} else if firstResponder!.tag == 3 {
testVar = Int(textFieldFour.text!)


func findActiveResponderFrame(view:UIView)->UIView?{
if view.isFirstResponder {
return view
} else {
for sub in view.subviews {
if let subView = sub as? UIView,
let found = findActiveResponderFrame(view: subView){
return found
return nil

Answer Source

The should return delegate method is only called when the user types return when the text field is first responder. You've added a tap gesture which ends editing programmatically - this won't call any delegate methods.

You need to restructure your logic, and find which of your text fields is first responder when dismissKeyboard is called, and get the values then.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download