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:

About these ads

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

  1. Pingback: Add the Return Key for UIKeyboardTypeNumberPad | Iphone Dev Center

  2. Pingback: [iPhone Dev] 숫자 키보드에 “Done” 버튼 넣기 | Alones world

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s