Colin Murgatroyd Colin Murgatroyd - 2 months ago 24
Swift Question

textField method of UITextFieldDelegate not being called

I think I'm probably doing something stupid but I'm going to ask the question anyway.
I cannot see the UITextFieldDelegate method textField being called. I've created a simple program with print statements showing all other delegate methods get called okay, but not this one. Here's the program code:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

//MARK: Properties
@IBOutlet weak var testTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

testTextField.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
print("textFieldShouldReturn")
textField.resignFirstResponder()
return true
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
print("textFieldShouldBeginEditing")
return true
}

func textFieldDidBeginEditing(textField: UITextField) {
print("textFieldDidBeginEditing")
print("Leaving textFieldDidBeginEditing")
}

func textField(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("textField")
print("Leaving textField")
return true
}

func textFieldDidEndEditing(textField: UITextField) {
print("textFieldDidEndEditing")
print("textField = \(textField.text)")
print("Leaving textFieldDidEndEditing")
}
}


Ands that's it. I have a ViewController with a UITextField added in Interface Builder. Entering text shows the other delegate methods are being called okay. I'm using Xcode 7.3.1.
Any help much appreciated and apologies up front if this is a dumb question - which I expect it is.

Answer

I think you are facing the issue because of the typo in the function.

This is what you are using:

func textField(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {...}

This is how the function should be:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {...}