DRHTextFieldWithCharacterCount override delegate

Using UITextFieldDelegate with custom class

Stan Ostrovskiy

--

If you don’t want your ViewController to override this delegate, simply dont’ assing its delegate to self. However, his will block you from using other UITextFIeldDelegate methods for your DRHTextFieldWithCharacterCount inside this ViewController.

If you want to use other UITextFIeldDelegate methods for your custom textField in ViewController, you can create a custom delegate for this textField:

protocol DRHTextFieldWithCharacterCountDelegate: class {   // some of UITextFieldDelegate methods you might need to use   func didEndEditing()
func didBeginEditing()
// another handy method to use (for example, to display an error message when the limit is reached)
func didReachCharacterLimit(reach: Bool)
}

Now, just create a delegate inside DRHTextFieldWithCharacterCount class:

weak var drhDelegate: DRHTextFieldWithCharacterCountDelegate?

I will explain how to create and use delegates in one of my next tutorials

Next, you need to add those methods for the corresponding UITextFieldDelegate methods:

extension DRHTextFieldWithCharacterCount: UITextFieldDelegate {func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {   // existing code for counter
...
if newLength <= lengthLimit {
...
// new code for delegate method:
drhDelegate?.didReachCharacterLimit(false)
} else {
drhDelegate?.didReachCharacterLimit(true)

....
}
return newLength <= lengthLimit
}
func textFieldDidEndEditing(textField: UITextField) {
// call new delegate methods
drhDelegate?.didEndEditing()
}
func textFieldDidBeginEditing(textField: UITextField) {
// call new delegate methods
drhDelegate?.didBeginEditing()
}
}

Having that set up, you need to assign a custom text field delegate to self in your ViewController class:

override func viewDidLoad() {
super.viewDidLoad()
customTextField?.drhDelegate = self
}

Do not misprint it for customTextField?.delegate = self. This will override the delegate and the counter won’t work in this ViewController. We are using a custom drhDelegate here.

Finally, create a ViewController extension and use those methods:

extension ViewController: DRHTextFieldWithCharacterCountDelegate {   func didEndEditing() {   }   func didBeginEditing() {   }   func didReachCharacterLimit() {
// do whatever you want when the character limit is reached
}
}

Hope that helps!

PS. I updated my Github repository with these changes, if you want to see this in action.

--

--

Stan Ostrovskiy
Stan Ostrovskiy

No responses yet