gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:53:31 25 4
gpt4 key购买 nike

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

我想在键盘出现时为其向上移动设置动画。

但是我的实现:

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

如何正确设置过渡动画?

最佳答案

一些事情,首先你可以 Hook 键盘移动的动画循环,这样你的动画就会在同一时间/持续时间内动画。

其次,不是添加和删除约束(这将导致您的 View 在没有动画的情况下捕捉到位),而是更新动画 block 内约束的常量值。这是我在 Objective-C 中使用的一个片段,swift 版本应该是微不足道的。

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

}];

关于ios - 出现键盘时移动垂直居中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34302002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com