I have implemented a container view in my UIViewController
then placed a UITableViewController
within it. This table contains static rows that contain a couple UITextField
s. Now I have would like to detect when the user presses the return key on the keyboard when one of those text field's is the first responder - in the containing view controller not the table view controller. Is this possible, or is it only possible to know that in the controller the object exists in?
I attempted to do this but textFieldShouldReturn
is not called. I conform to UITextFieldDelegate
in the view controller's .h file, I implemented textFieldShouldReturn
, and in order to set the delegate
for the text fields I get a reference to the container view in prepareForSegue
then set the delegate
for those text fields to self
. (I made them public so they can be accessed in the containing controller.)
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"Show Container View"]) {
if ([segue.destinationViewController isKindOfClass:[ContainerTableViewController class]]) {
self.ctvc = segue.destinationViewController;
self.ctvc.firstTextField.delegate = self;
self.ctvc.secondTextField.delegate = self;
}
}
}
Why isn't textFieldShouldReturn
called when I hit return on the keyboard?
Why isn't textFieldShouldReturn called when I hit return on the keyboard?
Because you are not the delegate of the text field. That, in turn, is because you are setting the delegate too soon. You are saying:
self.ctvc.firstTextField.delegate = self;
self.ctvc.secondTextField.delegate = self;
But you are saying it in prepareForSegue
. At that time, ctvc
has not loaded its view yet, and firstTextField
and secondTextField
are still both nil. So your code here has no effect.