Ad

Getting Keyboard Events For IOS UIView Which Contains A TextField

- 1 answer

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)

Ad

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

Ad
source: stackoverflow.com
Ad