Reputation: 1348
I created a custom text field and call a function every time the user type on it, the problem is how can I know what function was going to call.
Here is my code for custom UITextField that call a function every type.
class CustomTextField: UITextField, UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
NSObject.cancelPreviousPerformRequests(
withTarget: self,
selector: #selector(callFunction),
object: textField)
self.perform(
#selector(callFunction),
with: textField,
afterDelay: 0.5)
return true
}
@objc func callFunction(textField: UITextField) {
functionToBeCall()
}
}
As you can see in my code, I need that functionToBeCall()
to be change in every class I use it, and that class was reusable so I can't set a static method in it. How can I achieve that?
Upvotes: 0
Views: 56
Reputation: 154603
Use delegation:
protocol CustomTextFieldDelegate: class {
func customTextFieldDidChange(_ customTextField: CustomTextField)
}
class CustomTextField: UITextField, UITextFieldDelegate {
weak var customDelegate: CustomTextFieldDelegate?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
NSObject.cancelPreviousPerformRequests(
withTarget: self,
selector: #selector(callFunction),
object: textField)
self.perform(
#selector(callFunction),
with: textField,
afterDelay: 0.5)
return true
}
@objc func callFunction(textField: UITextField) {
customDelegate?.customTextFieldDidChange(self)
}
}
Any class that uses a CustomTextField
should adopt the CustomTextFieldDelegate
protocol, implement the callback function, and set itself as the customDelegate
on the CustomTextField
.
Example Usage:
class ViewController: UIViewController, CustomTextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let customTextField = CustomTextField(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
view.addSubview(customTextField)
customTextField.customDelegate = self
}
func customTextFieldDidChange(_ customTextField: CustomTextField) {
print("custom field was changed")
}
}
Upvotes: 3