您的位置:首页 > 移动开发 > IOS开发

处理iOS键盘通知

2015-12-24 10:42 447 查看

常见的键盘通知

UIKeyboardWillShowNotification 显示键盘的时候立即发出该通知

UIKeyboardDidShowNotification 显示键盘后才发出该通知

UIKeyboardWillHideNotification 键盘即将消失的时候立即发出该通知

UIKeyboardDidHideNotification 键盘消失后才发出该通知

UIKeyboardWillChangeFrameNotification 键盘的frame值发生变化的时候立即发出该通知

UIKeyboardDidChangeFrameNotification 键盘的frame值发生变化后才发出该通知

通知中携带的信息

通知的userInfo中包含了一些键盘frame以及动画相关的信息,字典的key如下:

NSString *const UIKeyboardFrameBeginUserInfoKey; //对应的value类型NSValue,存储一个CGRect结构(动画开始时的frame值)

NSString *const UIKeyboardFrameEndUserInfoKey; //对应的value类型NSValue,存储一个CGRect结构(动画结束后的frame值)

NSString *const UIKeyboardAnimationDurationUserInfoKey; //对应的value类型NSNumber,存储一个包含键盘进入或离开屏幕的UIViewAnimationCurve结构

NSString *const UIKeyboardAnimationCurveUserInfoKey; //对应的value类型NSNumber,存储一个包含键盘动画时间的double值,时间以秒为单位。

例:UIKeyboardWillChangeFrameNotification的userInfo值:

userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 0;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {480, 162}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {240, 401}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {240, 239}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{158, 0}, {162, 480}}";
UIKeyboardFrameChangedByUserInteraction = 0;
UIKeyboardFrameEndUserInfoKey = "NSRect: {{158, 0}, {162, 480}}";
}


iPhone和iPad的通知区别

当在英文和中文输入法之间切换时,iPhone中并不会产生UIKeyboardWillChangeFrameNotification和UIKeyboardDidChangeFrameNotification通知,而iPad中会产生。

iOS 的键盘在iPad上可以拆分(Split)和浮动(Undock),在切换键盘为拆分或者浮动时,会有Hide Notification,合并键盘时才会有Show Notification。拆分或浮动时键盘是隐藏的。

在拆分和浮动状态下,隐藏和显示键盘,不会收到Show和Hide Notification,只会收到UIKeyboardWillChangeFrameNotification和UIKeyboardDidChangeFrameNotification。

如果要在键盘显示时做一些操作,可以这样写:

[[NSNotificationCenter defaultCenter]
addObserverForName:UIKeyboardDidChangeFrameNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification * notification) {
CGRect keyboardEndFrame = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect screenRect = [[UIScreen mainScreen] bounds];
if (CGRectIntersectsRect(keyboardEndFrame, screenRect)) {
// Keyboard is visible
} else {
// Keyboard is hidden
}
}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: