3

我正在使用 Josh 在此问题中描述的方法将工具栏添加到 iPhone 键盘的顶部。基本上,这个想法是:

  • 将视图控制器添加为通知的观察者UIKeyboardWillShowNotification及其UIKeyboardWillHideNotification初始化方法
  • 每当发布这些通知时,将工具栏与键盘一起动画到/关闭屏幕

我在屏幕上也有多个 UITextFields,所有这些都在选择编辑时成为第一响应者,并在编辑完成时退出第一响应者(用户点击另一个文本字段,关闭任何文本字段,或者按键盘上的“完成” - 我已经textFieldShouldReturn:覆盖到resignFirstResponder)。

不过,我遇到了一个问题,因为每次我在文本字段之间切换时都会发布通知。例如,如果用户正在编辑文本字段 A,然后完成它并点击文本字段 B,A 辞去第一响应者,B 成为第一响应者。但是,这也会将“将显示”和“将隐藏”通知发布到我的视图控制器。

所有这一切的最终结果是,虽然工具栏在第一个文本字段的键盘上出现,而在最后一个文本字段的键盘上消失,但每次用户在文本之间切换时,它似乎都会滑入和滑出键盘字段。

如果键盘实际上要显示或隐藏,有没有办法只响应“将{显示,隐藏}”通知?换句话说,我如何忽略不会导致键盘可见状态改变的通知?

4

2 回答 2

4

您需要创建一个 BOOL ivar 来跟踪键盘是否已经可见,因此您将充分利用所有 UITextField 委托方法 :) 具有多个文本字段的工具栏可能很棘手,但您非常关闭!

于 2009-07-10T03:59:17.663 回答
4

跟进 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];
}
于 2009-07-10T04:54:20.907 回答