Getting Keyboard Events For IOS UIView Which Contains A TextField
I find it is pretty straightforward to add a gesture recogniser to a textField i.e. textField.EditingDidBegin // textField.EditingDidEnd etc.
However, I have created a new view controller extending a UIView which contains a textField which I use in quite a few places.
I need to create a new gesture recognizer to change the behaviour of my EditingDidBegin // EditingDidEnd on the UITextField contained in my class. I am struggling to this because I am not sure how to override the gesture recognizer already attached to the text field as well as not being able to access that TextField from another class (obviously)
Answer
Assuming you have a custom view like MyView: UIView
and using it in another ViewController
.
Declare protocol to handle TextField events in another ViewController
or View
from MyView
.
protocol MyViewDelegate {
func fieldBeginEditin(_ aTextField: UITextField)
func fieldEndEditin(_ aTextField: UITextField)
}
Your custom view
class MyView: UIView, UITextFieldDelegate {
//assume you have textfield object here
var _textField: UITextField!
var delegate: MyViewDelegate?
override func awakeFromNib() {
super.awakeFromNib()
setupInterface()
}
func setupInterface() {
if _textField == nil {
_textField = UITextField(frame: .zero)
_textField.delegate = self
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.fieldEndEditin(textField)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
delegate?.fieldEndEditin(textField)
}
}
Handling Textfield events from where you have added your custom view
class ViewController: UIViewController, MyViewDelegate{
var myView = MyView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
myView.delegate = self
}
func fieldEndEditin(_ aTextField: UITextField) {
print(#function)
}
func fieldBeginEditin(_ aTextField: UITextField) {
print(#function)
}
}
NOTE: apply the same logic with C# code
Related Questions
- → How to Fire Resize event after all images resize
- → JavaScript in MVC 5 not being read?
- → URL routing requires /Home/Page?page=1 instead of /Home/Page/1
- → Getting right encoding from HTTPContext
- → How to create a site map using DNN and C#
- → I want integrate shopify into my mvc 4 c# application
- → Bootstrap Nav Collapse via Data Attributes Not Working
- → Shopify api updating variants returned error
- → Get last n quarters in JavaScript
- → ASP.NET C# SEO for each product on detail page on my ECOMMERCE site
- → SEO Meta Tags From Behind Code - C#
- → onchange display GridView record if exist from database using Javascript
- → How to implement search with two terms for a collection?