Reputation: 15927
Is there an iPhone equivalent for the NSResponder
methods -selectNextKeyView
or -nextValidKeyView
from Mac OS X? I know about the -becomeFirstResponder
method, but finding out which view to call that on is not very pretty when view hierarchies get more complicated.
There must be some kind of way to find this out as when I press tab when in the iPhone Simulator, focus does properly go to the next UITextField
. This made me wonder what exactly happens when I press tab. Any ideas?
Update: This does exactly what I want, but _nextKeyResponder
is private API, so a no-no. Is there any way to do a 'fake' tab key press without using private API?
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// Try to find next responder
UIView *nextResponder = (UIView *)[self.view _nextKeyResponder];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
[self.tableView scrollRectToVisible:[self.tableView convertRect:[nextResponder frame] fromView:nextResponder] animated:YES];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
Upvotes: 10
Views: 2543
Reputation: 1276
I'm surprised nobody else appears to have solved this on iOS.
I devised a solution that handles both Tab and Shift+Tab to go forward and backward to any field you want on iOS, and doesn't use any private APIs.
Here is the write-up: http://weaklyreferenced.wordpress.com/2012/11/13/responding-to-the-tab-and-shift-tab-keys-on-ios-5-ios-6-with-an-external-keyboard/
Upvotes: 0
Reputation: 4053
There is not a public iOS equivalent for NSResponder
's -selectKeyView
or -nextValidKeyView
.
When the first responder is an instance of UITextField
, pressing tab instantiates a private subclass of UIEvent
which is passed to -[UIApplication sendEvent:]
, which in turn calls -[UIView _nextKeyResponder]
.
-[UIView _nextKeyResponder]
doesn't work quite the way you think it does. It treats the key view chain as a loop, so your else
block will never be reached. For the same reason, even if there was a public API for synthesizing keyboard events, you probably wouldn't want to use it.
Instead, you probably want something more like UIWebView
's UIToolbar
-based form input accessory. Its buttons can be enabled and disabled when appropriate, and its delegate handles the actual button press actions.
To implement such a delegate in a general way, however, it might be helpful to look at how -[UIView _nextKeyResponder]
is implemented.
Upvotes: 12
Reputation: 96937
In the UITextField
delegate -textFieldDidEndEditing:
, switch between the various text fields (for example, by testing the text field's tag
property).
When you match one text field, set another text field or other control to become the next responder.
Upvotes: 0