适应iOS中的键盘高度变化

基本原理:通过获取键盘消息的开始状态、结束状态,以及变化周期,可以计算出具体的Y偏移,从而在相同时间里做相同偏移量。

代码如下:

 

[plain][/plain] view plaincopy

  1. – (void)regNotification
  2. {
  3.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
  4. }
  5. – (void)unregNotification
  6. {
  7.     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
  8. }
  9. #pragma mark – notification handler
  10. – (void)keyboardWillChangeFrame:(NSNotification *)notification
  11. {
  12.     NSDictionary *info = [notification userInfo];
  13.     CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  14.     CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
  15.     CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  16.     CGFloat yOffset = endKeyboardRect.origin.y – beginKeyboardRect.origin.y;
  17.     CGRect inputFieldRect = self.inputview.frame;
  18.     inputFieldRect.origin.y += yOffset;
  19.     [UIView animateWithDuration:duration animations:^{
  20.         self.inputview.frame = inputFieldRect;
  21.     }];
  22. }

标签