繁体   English   中英

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

[英]Moving Vertically Centered Content when Keyboard appears

我有一个垂直居中的注册表格。

当键盘出现时,我想为其上移动画。

但是我的实现:

1-移除Align center Y to: Superview

2-钩入键盘框架

3-基于键盘框架安装约束

进行非常静态的位移,没有动画。

@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)
    }
}

如何正确设置过渡动画?

结合几件事,首先您可以加入键盘移动的动画周期,以便动画可以同时/持续进行动画处理。

其次,不要添加和删除约束(这将导致视图在不进行动画处理的情况下就位),而是更新动画块内约束的常量值。 这是我在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