iOS autolayout 下 键盘 遮挡 处理 keyboard handler move up

阅读更多

  

在ios 中  由于键盘出现后会遮挡屏幕下面区域, 所以会有需求当键盘出现的时候 提升下方的view

 

在autolayout 下  之前的计算x,y的方法很可能没法正常工作,需要新的解决办法

 

 

新办法的基本思想是调整需要上移的view的bottomConstraint, 让他加上键盘的高度

 

 

具体逻辑是

 

1. 监听键盘事件UIKeyboardWillShowNotification

2. 获取键盘高度, 注意要获取 UIKeyboardFrameEndUserInfoKey 这个值,其他的值在英文键盘也许OK,但在中文键盘下会出错

3. 提升目标view的bottomConstraint, 要注意的是rotation时 keyboard的高会变, 所以要注意更新

 

 

上代码

   [[NSNotificationCenter defaultCenter] addObserverForName: UIKeyboardWillShowNotification
     
                                                      object: nil
                                                       queue: nil
                                                  usingBlock: ^(NSNotification *note){
         NSDictionary* userInfo = note.userInfo;
         CGRect keyboardFrame = [[userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue];
         //keyboardSlideDuration is an instance variable so we can keep it around to use in the "dismiss keyboard" animation.
         keyboardSlideDuration = [[userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey] floatValue];
         
         // keyboard height will change during rotation, so bottomConstraint need to keep update
         if (self.bottomConstraint.constant != keyboardFrame.size.height) {
             //             CLog(@"move up");
             self.bottomConstraint.constant = keyboardFrame.size.height;
             
             [UIView animateWithDuration: keyboardSlideDuration
                                   delay: 0
                                 options: 0
                              animations:^{
                                  [self.view layoutIfNeeded];
                              }
                              completion: nil
              ];
         }
         
     }
     ];
    
    [[NSNotificationCenter defaultCenter] addObserverForName: UIKeyboardWillHideNotification
                                                      object: nil
                                                       queue: nil
                                                  usingBlock: ^(NSNotification *note){
          self.bottomConstraint.constant = 0;
          [UIView animateWithDuration: keyboardSlideDuration
                                delay: 0
                              options: 0
                           animations:
                                       ^{
                                           [self.view layoutIfNeeded];
                                                                                                  
                                       }
                           completion: nil];
        }
     ];
    

 

 

 

 

 

你可能感兴趣的:(iOS autolayout 下 键盘 遮挡 处理 keyboard handler move up)