美文网首页
iOS View跟随键盘一起动画

iOS View跟随键盘一起动画

作者: Fisher123 | 来源:发表于2018-06-22 11:13 被阅读0次
  1. 先注册键盘监听,代码如下:
- (void)registerForKeyboardNotification {
    // 键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillChangeFrameNotification object:nil];
    // 键盘隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

  1. 键盘出现时动画,代码如下:
// 键盘出现时
- (void)keyboardWillShow:(NSNotification*)aNotification {    
    NSDictionary *info = [aNotification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    UIViewAnimationCurve curve = [aNotification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    CGRect endRect = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 更新officialBottomView位置
    CGRect newFrame = self.officialBottomView.frame;
    if (isIPhoneX) {
        newFrame.origin.y = endRect.origin.y - 80 - 90;
    }
    else {
        newFrame.origin.y = endRect.origin.y - 80 - 70;
    }
    UIViewAnimationOptions options = (UIViewAnimationOptions)curve << 16;
    [UIView animateWithDuration:duration delay:0.0 options:options animations:^{
        self.officialBottomView.frame = newFrame;
    } completion:NULL];
}

  1. 键盘隐藏时动画,代码如下:
// 当键盘隐藏时
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    NSTimeInterval duration = [aNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [aNotification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    CGRect endRect = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 复原officialBottomView位置
    CGRect newFrame = self.officialBottomView.frame;
    if (isIPhoneX) {
        newFrame.origin.y = self.view.frame.size.height - officialBottomViewHeight - 34;
    }
    else {
        newFrame.origin.y = self.view.frame.size.height - officialBottomViewHeight;
    }
    UIViewAnimationOptions options = (UIViewAnimationOptions)curve << 16;
    [UIView animateWithDuration:duration delay:0.0 options:options animations:^{
        self.officialBottomView.frame = newFrame;
    } completion:NULL];
}

相关文章

网友评论

      本文标题:iOS View跟随键盘一起动画

      本文链接:https://www.haomeiwen.com/subject/kiqkyftx.html