Abhinav Jha
Abhinav Jha

Reputation: 345

Can we call delegate in an extension of UITextField

I am not able to find any way to call the delegate in the below code and without delegate the textFieldDidBeginEditing method cant be called

import UIKit

class ModifiedTextField: UITextField { }

extension UITextField: UITextFieldDelegate{

func fieldEmptyError(value: Bool){

    let textFieldVal = "\(self.placeholder!)"

    if (value){
        layer.borderColor = UIColor.red.cgColor
        layer.cornerRadius = 5.0
        layer.masksToBounds = true
        layer.borderWidth = 1
        pulsate()
        textFieldOrigVal(string: textFieldVal, borderColor: UIColor.red)
    }else {

        textFieldOrigVal(string: textFieldVal, borderColor: UIColor.lightGray)
        layer.borderWidth = 0.2
        layer.borderColor = UIColor.lightGray.cgColor

    }
}


public func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.fieldEmptyError(value: false)
}


}

Upvotes: 1

Views: 1992

Answers (2)

Vikky
Vikky

Reputation: 936

First you need need to replace your extension as

extension ModifiedTextField : UITextFieldDelegate{}

But you said that you get error doing this

You get error because fieldEmptyError method is available with ModifiedTextField not UITextField and you are calling method as textField.fieldEmptyError(value: false)

So you need to call method directly inside your extension

extension ModifiedTextField : UITextFieldDelegate{
func textFieldDidBeginEditing(_ textField: UITextField) {
    fieldEmptyError(value: false)

}
}

And do not forget to set delegate You can do it by storyboard or programmatically

override func awakeFromNib() {
    delegate = self
}

So finally you entire code looks something like this

import UIKit
class ModifiedTextField: UITextField {

override func awakeFromNib() {
    delegate = self
}
 }
 extension ModifiedTextField : UITextFieldDelegate{
func textFieldDidBeginEditing(_ textField: UITextField) {
    fieldEmptyError(value: false)

}
func fieldEmptyError(value: Bool){

    let textFieldVal = "\(self.placeholder!)"

    if (value){
        layer.borderColor = UIColor.red.cgColor
        layer.cornerRadius = 5.0
        layer.masksToBounds = true
        layer.borderWidth = 1
        pulsate()
        textFieldOrigVal(string: textFieldVal, borderColor: UIColor.red)
    }else {

        textFieldOrigVal(string: textFieldVal, borderColor: UIColor.lightGray)
        layer.borderWidth = 0.2
        layer.borderColor = UIColor.lightGray.cgColor

    }
}
}

Upvotes: 4

David Kadlcek
David Kadlcek

Reputation: 476

Try this. I hope it helps you.

class ModifiedTextField { 
   viewDidLoad() {
       super.viewDidLoad()
       yourTextField.delegate = self
   }
}

extension ModifiedTextField: UITextFieldDelegate {

    public func textFieldDidBeginEditing(_ textField: UITextField) {
          // Your code, what happend
    }
}

Upvotes: 1

Related Questions