I\'m trying to add a \"done\" button to the UIKeyboadnumpad, but with no success. What\'s wrong in my code?
the keyboard don\'t have the done button
To make it short: take a screenshot, cut out the whole backspace key, flip it horizotally, clear its backspace symbol in Photoshop and overlay it with the text that we want on our return key. We’ve chosen to label it DONE.
Now we have the image for our custom button’s UIControlStateNormal.
Repeat the whole procedure (with a touched backspace key when taking the screenshot) to get a second image for our button’s UIControlStateHighlighted
.
Here’s the result: <missing image>
Now back to coding:
First we need to know when the number pad is going to slide up on the screen so that we can plug our custom button before that happens.
Luckily there’s a notification for exactly that purpose and registering for it is as easy as:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
Don't forget to remove the observer from the notification center in the appropriate place once you're done with the whole thing:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Now we’re getting to the heart of it. All we have to do in the keyboardWillShow
method is to locate the keyboard view and add our button to it.
The keyboard view is part of a second UIWindow of our application as others have already figured out (see this thread).
So we take a reference to that window (it will be the second window in most cases, so objectAtIndex:1
in the code below is fine), traverse its view hierarchy until we find the keyboard and add the button to its lower left:
- (void)keyboardWillShow:(NSNotification *)note {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"]
forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"]
forState:UIControlStateHighlighted];
[doneButton addTarget:self action:@selector(doneButton:)
forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows]
objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@"UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
Voilà, that’s it!
The empty space for our button starts at coordinate (0, 163) and has the dimensions (106, 53).
The doneButton
method has to be written now of course, but that’s not hard any more. Just make sure that you call resignFirstResponder
on the text field that is being edited to have the keyboard slide down.
We’re “DONE”.