我在旋转设备时收到多个 UIKeyboardDidShowNotification 和 UIKeyboardDidHideNotification 通知,但我不知道为什么。
我有一个应用程序,可让您编辑每张图片的文本。(它在 UITextView 中。)大多数时候我需要向上滑动文本以便您可以在键盘上方看到它,然后在您完成编辑时将其向下滑动。然后我进行数据库更新以保存新文本。我使用通知来告诉我键盘何时显示以及何时消失。当用户点击键盘上的键盘关闭图标时,它在 iPad 上运行良好。如果用户滑动到下一页并且 iOS 关闭键盘,它也可以正常工作。由于 iPhone 和 iPod 没有键盘关闭键,所以我写了一个方法来在点击图片或背景时关闭键盘。它在那里也可以正常工作。但是,当我旋转设备时,我会收到多个隐藏和显示通知。我不知道为什么。
我没有得到一个 UIKeyboardDidHideNotification 通知,而是得到一个隐藏、一个显示、一个隐藏和一个显示。
2:39:44.200 Picts for SLPs[16533:907] keyboardDidHide called. Keyboard showing flag is YES.
2:39:51.751 Picts for SLPs[16533:907] keyboardDidShow called. Keyboard showing flag is NO.
2:39:55.224 Picts for SLPs[16533:907] keyboardDidHide called. Keyboard showing flag is YES.
2:39:56.124 Picts for SLPs[16533:907] keyboardDidShow called. Keyboard showing flag is NO.
我在下面发布了相关代码。它主要取自 StackOverflow 帖子(谢谢大家)。
在我显示图片的类中,我在初始化时开始通知。
- (id)initWithParentView:(UIView *)parentview {
self = [super init];
if (self) {
_parentView = parentview;
if (ALLOW_DATABASE_EDITING) [self startNotifications];
}
return self;
}
- (void)startNotifications {
// Listen for keyboard appearances and disappearances
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
}
当用户点击图片时,View Controller 会调用 View 中的 hideKeyboard 方法。
- (void)dismissKeyboard {
if (self.showArtic.keyBoardIsShowing) {
[self.showArtic hideTheKeyboard];
}
}
resignFirstResponder 发送关闭键盘的通知
- (void)hideTheKeyboard {
id <ShowArticDelegate> SA_delegate = _delegate;
// Don't update the database when there is no text.
if ( ![self.editableTextView.text isEqualToString:@""] ) {
[SA_delegate updateTextInDatabase:self.editableTextView.text];
}
[self.editableTextView resignFirstResponder];
}
这些方法响应通知。
- (void)keyboardDidHide:(NSNotification *)notification {
NSLog(@"keyboardDidHide called. Keyboard showing flag is %@.", self.keyBoardIsShowing ? @"YES" : @"NO");
self.keyBoardIsShowing = NO;
// Move the text, update the database
}
- (void)keyboardDidShow:(NSNotification *)notification {
NSLog(@"keyboardDidShow called. Keyboard showing flag is %@.", self.keyBoardIsShowing ? @"YES" : @"NO");
self.keyBoardIsShowing = YES;
// Move the text
}