Skip to content

Instantly share code, notes, and snippets.

@henrik
Created June 27, 2010 11:48
Show Gist options
  • Save henrik/454844 to your computer and use it in GitHub Desktop.
Save henrik/454844 to your computer and use it in GitHub Desktop.
Locating the keyboard (UIKeyboard) on iOS 4, to e.g. add a custom button.
- (void)someSetupMethod {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
}
- (void)someTeardownMethod {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
- (void)keyboardWillShow {
// We must perform on delay (schedules on next run loop pass) for the keyboard subviews to be present.
[self performSelector:@selector(addHideKeyboardButtonToKeyboard) withObject:nil afterDelay:0];
}
- (void)addHideKeyboardButtonToKeyboard {
// Locate non-UIWindow.
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
if (!keyboardWindow) return;
// Locate UIKeyboard.
UIView *foundKeyboard = nil;
for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
// iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
}
if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) {
foundKeyboard = possibleKeyboard;
break;
}
}
if (foundKeyboard) {
// Add the button to foundKeyboard.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment