One strategy to learn here is to override the setDelegate method: and then do some message forwarding. You can use [super setDelegate: self]
to make sure your calls receive the first dibs in delegate messages. When overriding setDelegate: set the internal ivar, e.g.
- (void) setDelegate: (id<UITextFieldDelegate>) internalDelegate; { [setInternalDelegate: internalDelegate]; }
Then, for each of the UITextField delegate methods, do your thing before forwarding according to the delegate message, for example
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; {
Typically, you will want to override all delegate methods, even if for most of them all you do is straightforward.
Update . You note in the comments that the forwarding approach raises issues. If so, then traditional delegation is the way to go. (And, in general, this is the way to go - although I used the forwarding delegate once or twice, I'm not sure if it was absolutely important with retroactivity, and I did not check if I had it done with UITextField. @ Scott Korskadden neither recommends nor recommends.)
The most common pattern is to force the ViewController to keep track of the view in which the UITextField
is a sub delegate. You do not say in your answer if there is any reason why you need to work with a subclass. If you are packing interesting things in a UITextField
, then it can be, although you can always suggest a different poster and create a companion class for the UITextField
that will work and use this as a delegate. In any case, if necessary, you can always force the delegate object to call additional methods in your UITextField
subclass, for example.
// in the delegate object class - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; { [delegate doSomeExtraThingInTheTextFieldSubclassThatItSeemsToMakeSenseToDoThereRatherThanHere]; // maybe that it, or maybe this object also wants to do something here... }