Reputation: 7123
I'm building custom UIView that takes in initialization array of input fields UITextField
or UITextView
. I need this custom view to be notified when input field begin editing without setting the delegate.
UITextField
I came up with an idea by adding observer for the editing
property. Do you have other Ideas?editing
in UITextView
so what should I do.The idea is that I need this custom view as a standalone and let users free to set the delegate in their UIViewControllers
Upvotes: 1
Views: 1113
Reputation: 777
Here's one approach that may allow for sending a notice to this custom UIView without needing to set it as a delegate:
import UIKit
class SelfAwareTextField : UITextField, UITextFieldDelegate {
//
// Other delegate for this textfield
//
var otherDelegate: UITextFieldDelegate? = nil;
//
// Set weak reference to parent UIView
//
weak var parentView: UIView!
//
// Set the initializer
//
init(parentView pv: UIView, frame: CGRect) {
parentView = pv;
super.init(frame: frame);
//
// Do some custom initialization...
//
// Make this textfield a delegate to itself
self.delegate = self;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setDelegate( delegate _otherDelegate: UITextFieldDelegate ){
otherDelegate = _otherDelegate;
}
//
// Write the textFieldDidBeginEditing method such that it
// also calls the otherDelegate in the event it exists
// and has this method defined
//
func textFieldDidBeginEditing(_ textField: UITextField){
//
// Do stuff based on this textfield knowing it is starting to be used
//
// ....
//
//
// Do stuff for parent UIView
// ...
// (parentView as! CustomView).notified() // or something like this
//
//
// Do stuff for the other delegate
//
otherDelegate?.textFieldDidBeginEditing?(textField);
}
// Do similar thing as above for other methods in UITextFieldDelegate protocol
}
The thought is that you make this textfield a delegate to itself so it knows when each of it's delegate methods are being called. Then in each call to these delegate methods, you can do something with the custom UIView and any other delegate you want associated with this textfield.
Upvotes: 0
Reputation: 4218
Another method is to observe UITextView
's notification UITextViewTextDidBeginEditingNotification
and
UITextField
's notification UITextFieldTextDidBeginEditingNotification
Upvotes: 2
Reputation: 7123
I came up with a solution, I used UIKeyboardWillShowNotification
to receive notification when keyboard is about to show, then loop over the fields I have and check for isFirstResponder()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil)
and then:
@objc private func keyboardWillBeShown(notification:NSNotification){
for field in fields{
if field.isFirstResponder(){
// handle begin editing here
}
}
}
Upvotes: -1