iPhone – Add the Return Key for UIKeyboardTypeNumberPad in iPhone SDK 4

A few months ago, i have a post talking about adding a return button for UIKeyboardTypeNumberPad.
iPhone – Add the Return Key for UIKeyboardTypeNumberPad

But that only works in iOS SDK <= 3.2M. After i upgrade it to 4.0, that feature was broken.

It is found that the we have add the observer to the UIKeyboardDidShowNotification instead of UIKeyboardWillShowNotification. Moreover, the view prefix is changed from <UIKeyboard to <UIPeripheralHostView. Here comes the code.

- (void)viewWillAppear:(BOOL)animtated {

	// Register the observer for the keyboardWillShow event
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
	
}

- (void)viewWillDisappear:(BOOL)animtated {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardWillShow:(NSNotification *)notification {
	// create custom buttom
	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(textFieldShouldReturn:) 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:@"<UIPeripheralHostView"] == YES) {
			[keyboard addSubview:doneButton];
		}
	}
}

-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {
	// Set the FirstResponder of the UITextField on the layout
	[self.textField resignFirstResponder];
	return YES;
}

 

But this is not the best approach as you will find that the return button will appear after the keyboard is shown. If this is not what you need, you can take a look in the following links.

 

Done =)

Reference:

2 thoughts on “iPhone – Add the Return Key for UIKeyboardTypeNumberPad in iPhone SDK 4”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.