ios开发键盘自适应高度

2019-05-25  本文已影响0人  WY_260f

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

  [[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];

}

上一篇 下一篇

猜你喜欢

热点阅读