我正在尝试在键盘出现/更改时将UITextView移动到键盘上方。假设我现在使用英文键盘,然后直接切换到中文键盘(比标准的英文键盘高)。在这种情况下,我的文本视图总是显示得太高了。我在应用程序接收到UIKeyboardDidShowNotification时调整文本视图的位置(使用UIKeyboardFrameEndUserInfoKey来获取高度)。但是经过一些研究,我发现UIKeyboardDidShowNotification会被多次调用,并且往往伴随着不正确的键盘尺寸(我已经使用NSLog记录了userInfo字典)。我在ViewWillAppear中注册键盘通知,在ViewWillDisappear中取消注册。我无法确定是什么原因导致该通知多次触发;我理解这个通知应该只在键盘最终显示后触发一次。另外需要说明的是:我已经在响应UIKeyboardDidShowNotification的方法中记录了“self”,它实际上总是相同的视图控制器对象。
即使该通知多次触发,我仍然不明白为什么有些通知的键盘高度会有所不同。其中一个通知始终具有正确的高度,但当它不是最后一个触发的通知时,文本视图就会出错。如果您能提供任何进一步排除故障的提示,我将不胜感激!
编辑:经过更多测试,似乎这是特定于中文键盘的问题。每当我从英语切换到中文时,我会收到三个UIKeyboardWillShowNotifications:
2014-12-24 22:49:29.385 Example[1055:421943] info dictionary: {
UIKeyboardAnimationCurveUserInfoKey = 0;
UIKeyboardAnimationDurationUserInfoKey = 0;
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 252}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 460}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 442}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 352}, {320, 216}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 316}, {320, 252}}";
}
2014-12-24 22:49:29.408 Example[1055:421943] info dictionary: {
UIKeyboardAnimationCurveUserInfoKey = 0;
UIKeyboardAnimationDurationUserInfoKey = 0;
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 442}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 460}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 316}, {320, 252}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 352}, {320, 216}}";
}
2014-12-24 22:49:29.420 Example[1055:421943] info dictionary: {
UIKeyboardAnimationCurveUserInfoKey = 0;
UIKeyboardAnimationDurationUserInfoKey = 0;
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 288}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 442}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 424}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 316}, {320, 252}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 280}, {320, 288}}";
}
第一个高度正确为252,但接下来的两个高度为216和288是错误的。这种情况经常发生。
以下是几个片段,演示我如何管理通知订阅:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self registerForKeyboardNotifications];
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
}
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification object:nil];
}
keyboardDidHide()
和keyboardDidShow()
的代码吗? - Anirudha Mahale