跟进 Reed 的回答:我最终使用了以下实现。它使用 aBOOL
来跟踪控制器是否在 atextFieldShouldBeginEditing:
和textFieldDidBeginEditing:
message 之间,以及使用 ivar 来跟踪当前正在编辑的文本字段。
该实现假定接口具有以下内容,并具有适当的属性和@synthesize
标记。MyKeyboardToolbar 是 UIToolbar 的子类,具有自定义初始化程序来创建自己的按钮。
BOOL shouldBeginEditing;
UITextField *editingField;
MyKeyboardToolbar *keyboardBar;
和代码本身:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// Give up first responder so the keyboard goes away
[textField resignFirstResponder];
return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
self.shouldBeginEditing = YES;
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
self.shouldBeginEditing = NO;
self.editingField = textField;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
// Do things here with the edited data (e.g. save it somewhere)
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
self.editingField = nil;
}
// These methods are added as the observers to the notification center
- (void)keyboardWillShow:(NSNotification *)notification {
if(self.keyboardBar == nil) {
// Create and show the keyboard toolbar
}
}
- (void)keyboardWillHide:(NSNotification *)notification {
if(![self shouldBeginEditing]) {
// Animate the bar off the screen, if necessary
// Remove and dispense of the bar entirely
[self.keyboardBar removeFromSuperview];
self.keyboardBar = nil;
}
}
// This method's selector is given to the keyboard toolbar's Done button
- (void)didPressKeyboardBarDoneButton {
[self.editingField resignFirstResponder];
}