处理iOS键盘通知

常见的键盘通知

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的通知区别

  1. 当在英文和中文输入法之间切换时,iPhone中并不会产生UIKeyboardWillChangeFrameNotification和UIKeyboardDidChangeFrameNotification通知,而iPad中会产生。
  2. 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
        }
 }];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值