随着iOS中自定义键盘的引入,这个问题变得更加复杂。
简而言之,UIKeyboardWillShowNotification可以通过自定义键盘实现多次调用:
- 当苹果的系统键盘被打开(纵向)
- 发送的UIKeyboardWillShowNotification的键盘高度为224
- 当了Swype键盘被打开(纵向):
- 发送的UIKeyboardWillShowNotification的键盘高度为0
- 发送的UIKeyboardWillShowNotification的键盘高度为216
- 发送的UIKeyboardWillShowNotification的键盘高度为256
- 当SwiftKey键盘被打开(纵向):
- 发送的UIKeyboardWillShowNotification的键盘高度为0
- 发送的UIKeyboardWillShowNotification的键盘高度为216
- 发送的UIKeyboardWillShowNotification的键盘高度为259
为了在一个代码行中正确处理这些情况,您需要:
根据UIKeyboardWillShowNotification和UIKeyboardWillHideNotification通知注册观察者:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
创建一个全局变量以跟踪当前的键盘高度:
CGFloat _currentKeyboardHeight = 0.0f;
实现keyboardWillShow以对键盘高度的当前变化做出反应:
- (void)keyboardWillShow:(NSNotification*)notification {
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
CGFloat deltaHeight = kbSize.height - _currentKeyboardHeight;
_currentKeyboardHeight = kbSize.height;
}
注意:您可能希望为视图的偏移设置动画。该信息字典包含键的值UIKeyboardAnimationDurationUserInfoKey。此值可用于以与显示键盘相同的速度为更改设置动画。
将keyboardWillHide实现为reset _currentKeyboardHeight并对被关闭的键盘做出反应:
- (void)keyboardWillHide:(NSNotification*)notification {
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
_currentKeyboardHeight = 0.0f;
}
keyboardFrameBeginRect
为本地坐标,则可能会有所帮助。