那么在iOS下怎么判断键盘是否弹出以及如何获取键盘占据的宽高呢?
其实iOS提供了若干种键盘相关的通知事件:
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
UIKeyboardWillChangeFrameNotification
UIKeyboardDidChangeFrameNotification
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification
看名字基本就能猜出来意思:键盘被调起/键盘宽高发生改变/键盘收起
接下来我们通过一个例子来看看这些事件怎么用:
首先在viewController的viewDidAppear:中注册事件
- (void)viewDidAppear:(BOOL)animated { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; }
然后别忘了在合适的位置注销事件,让事件的注册/注销对称
- (void)viewWillDisappear:(BOOL)animated { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil]; }
ok注册完了事件就能在对应的方法中获得事件响应
- (void)keyboardFrameWillChange:(NSNotification*)aNotification { NSDictionary* info = [aNotification userInfo]; _kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; // do your job here }
当键盘的宽高发生改变时,keyboardFrameWillChange:就会得到响应,这时会接收到事件相关的notification,从这个notification中我们又可以拿到事件相关的属性,上面的方法里我们从userInfo中拿到了键盘的size,对应的key为UIKeyboardFrameEndUserInfoKey,拿到了宽高值我们就可以自己计算视图中其它元素该如何调整位置啦。
其它事件小伙伴们就自己尝试吧,今天就到这啦。