看过《UIKeyboardTypeNumberPad和丢失的return键》之后,你是否已经迫不及待地用上述的方法解决iPhone的NumberPad键盘的bug呢?
很不幸,这个解决方案真的不是完善的。如果在一个View Controller中存在多个Text Field,其中一个使用NumberPad键盘,而其他的不是,则你会遇到如下问题:
看到了吗?如果你先弹出NumberPad,则不管以后(编辑其他Text Field时)再弹出什么键盘,都会在左下角出现一个Done按钮!
这个问题怎么解决?
不要急,跟我做。
首先我们需要把Done按钮声明为View Controller的公开属性(声明为成员变量也可,反正我们不能让它仅仅是一个临时变量):
@property(retain,nonatomic)UIButton* doneButton;
⋯⋯
@synthesize doneButton;
在initWithNibName方法中,我们注册UIKeyboardDidShowNotification通知的观察者为self:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
然后实现 keyboardDidHide 和keyboardDidShow:方法:
-(void)keyboardDidHide:(NSNotification*)note{
if (self.doneButton) {
self.doneButton.hidden=YES;
}
}
- (void)keyboardDidShow:(NSNotification *)note {
//keyboard位于顶层窗口
NSInteger topWindow = [[[UIApplication sharedApplication] windows] count] - 1;
UIWindow *keyboard = [[[UIApplication sharedApplication] windows] objectAtIndex:topWindow];
// 在键盘第1次弹出时,创建按钮
if (self.doneButton == nil) {
self.doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.doneButton.hidden=YES;
// 向键盘中加入按钮
[keyboardaddSubview:self.doneButton];
// 设置按钮的位置在恰当的地方
[self.doneButton setFrame:CGRectMake(0, 427, 106, 53)];
// 设置按钮图片
[self.doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
[self.doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
// 当按钮按下时,触发doneButton方法
[self.doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
}
if (tfDynaPass.editing) {// 只有tfDynaPass会显示done按钮
self.doneButton.hidden = NO;
} else {
self.doneButton.hidden = YES;
}
[keyboard bringSubviewToFront:self.doneButton];
}
代码不解释,假设你都看过《UIKeyboardTypeNumberPad和丢失的return键 》一文了。
这是doneButton:方法,你应该知道在这里释放键盘。另外别忘了在这个方法里把Done按钮也隐藏掉:
- (void)doneButton:(id)sender {
self.doneButton.hidden=YES;
[tfDynaPass resignFirstResponder];
}
在.xib中,把所有TextField的delegate连接到File’s Owner。然后来实现TextFieldDelegate方法。现在你想让哪个TextField显示Done按钮都可以了:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if (tfDynaPass.editing) {// 只有tfDynaPass会显示done按钮
self.doneButton.hidden = NO;
} else {
self.doneButton.hidden = YES;
}
}
其中,tfDynaPass是需要在键盘上显示“Done”按钮的Text Field。