UITextField和键盘通知 - 奇怪的顺序

Bou*_*rne 16 iphone uitextfield uitextview uikeyboard ios

所以我已经设置了键盘外观事件的通知.现在让我们考虑一个UITextView和一个UITextField.

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

选择器是:

- (void)keyboardWillShow:(NSNotification *)notification {

        keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
}
Run Code Online (Sandbox Code Playgroud)

在一个UITextView的情况下,所述委托方法- (void)textViewDidBeginEditing:(UITextView *)textView烧制keyboardWillShow:方法.所以keyboardSize有键盘的实际大小,我可以在textview委托方法中使用它.

然而,在一个的UITextField的情况下,相应的委托方法- (void)textFieldDidBeginEditing:(UITextField *)textField进行烧制之前keyboardWillShow:方法.

为什么会这样?如何CGSize在textfield的情况下获得键盘,因为它现在只返回零,因为首先调用textfield委托而不是键盘选择器.

Bre*_*rge 5

我也遇到过同样的问题。尝试使用:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView              
Run Code Online (Sandbox Code Playgroud)


Lyn*_*ott 4

奇怪\xe2\x80\xa6 听起来像是苹果这边的一个错误。

\n\n

也许你可以延迟键盘弹出?不幸的是,这是我非常混乱的“解决方法”建议 - 您可以在选择文本字段时发送通知,但只有几分之一秒后才真正开始编辑,以便文本字段实际上是之前已知keyboardWillShow:的叫。例如:

\n\n
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {\n\n    // Notification corresponding to "textFieldSelected:" method\n    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_TEXT_FIELD_SELECTED object:nil userInfo:[[NSDictionary alloc] initWithObjectsAndKeys:textField, @"textField", nil]];\n\n    // "textFieldReallyShouldBeginEditing" is initially set as FALSE elsewhere in the code before the text field is manually selected\n    if (textFieldReallyShouldBeginEditing)\n        return YES;\n    else\n        return NO:\n}\n\n- (void)textFieldSelected:(NSNotification*)notification {\n\n    // Done in a separate method so there\'s a guaranteed delay and "textFieldReallyShouldBeginEditing" isn\'t set to YES before "textFieldShouldBeginEditing:" returns its boolean. \n    [self performSelector:@selector(startTextFieldReallyEditing:) withObject:(UITextField*)notification[@"textField"] afterDelay:.01];\n}\n\n- (void)startTextFieldReallyEditing:(UITextField*)textField {\n    textFieldReallyShouldBeginEditing = YES;\n\n    // To trigger the keyboard\n    [textField becomeFirstResponder];\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后,根据您创建通知的方式,您甚至可以在开始编辑之前插入此已知文本字段的值。

\n