简体   繁体   English

出现键盘时移动垂直居中的内容

[英]Moving Vertically Centered Content when Keyboard appears

I have a signup form that is vertically centered. 我有一个垂直居中的注册表格。

I would like to animate its move up when the keyboard appears. 当键盘出现时,我想为其上移动画。

However my implementation of: 但是我的实现:

1- Removing Align center Y to: Superview 1-移除Align center Y to: Superview

2- Hooking into the keyboard frame 2-钩入键盘框架

3- Installing a constraint based on the keyboard frame 3-基于键盘框架安装约束

Makes a very static displacement with no animation. 进行非常静态的位移,没有动画。

@IBOutlet weak var centerVertically: NSLayoutConstraint!
@IBOutlet weak var bottomDistance: NSLayoutConstraint!

(...)

func keyboardWillShow(notification: NSNotification) {
    var info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    bottomDistance.constant = keyboardFrame.size.height + 20

    UIView.animateWithDuration(2.0) { () -> Void in
        self.view.removeConstraint(self.centerVertically)
        self.view.addConstraint(self.bottomDistance)
    }
}

func keyboardWillHide(notification: NSNotification) {
    UIView.animateWithDuration(2.0) { () -> Void in
        self.view.removeConstraint(self.bottomDistance)
        self.view.addConstraint(self.centerVertically)
    }
}

How do I properly animate the transition ? 如何正确设置过渡动画?

Couple things, first you can hook into the animation cycle of the keyboard moving so that your animation will animate at the same time/duration. 结合几件事,首先您可以加入键盘移动的动画周期,以便动画可以同时/持续进行动画处理。

Secondly, instead of adding and removing your constraints (this will cause your view to snap in place without animating), update the constant value on the constraint inside the animation block. 其次,不要添加和删除约束(这将导致视图在不进行动画处理的情况下就位),而是更新动画块内约束的常量值。 Here is a snippet I am using in Objective-C, swift version should be trivial. 这是我在Objective-C中使用的代码片段,快速版本应该很简单。

[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        UIViewAnimationCurve curve = [[note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        double duration = [[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration:duration
                              delay:0
                         options:UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             [UIView setAnimationCurve:curve];
                             this.verticalConstraint.constant = 100.0f;
                             [this.view layoutIfNeeded];
                         }
                         completion:nil];
        [UIView commitAnimations];

    }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM