ios开发键盘自适应高度

一.为监听键盘高度添加两个观察者

  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];


  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];

二.实现监听到通知调用的方法

-(void)keyboardWillAppear:(NSNotification *)notification

{


  NSDictionary *info = [notification userInfo];


  //取出动画时长

  CGFloat animationDuration = [[info valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];

 //取出键盘位置大小信息

  CGRect keyboardBounds = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];


  //rect转换

  CGRect keyboardRect = [self.view convertRect:keyboardBounds toView:nil];



  //记录Y轴变化

  CGFloat keyboardHeight = keyboardBounds.size.height;


  //上移动画options

  UIViewAnimationOptions options = (UIViewAnimationOptions)[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;


  [UIView animateKeyframesWithDuration:animationDuration delay:0 options:options animations:^{

    self.table.transform = CGAffineTransformMakeTranslation(0, -keyboardHeight + 64);

  } completion:nil];

}

-(void)keyboardWillDisappear:(NSNotification *)notification

{

  NSDictionary *info = [notification userInfo];


  //取出动画时长

  CGFloat animationDuration = [[info valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];

  //下移动画options

  UIViewAnimationOptions options = (UIViewAnimationOptions)[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;


  //回复动画

  [UIView animateKeyframesWithDuration:animationDuration delay:0 options:options animations:^{

    self.table.transform = CGAffineTransformIdentity;

  } completion:nil];

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容