我的主视图底部有一个按钮,我希望在显示时用键盘为其添加动画效果。
我的按钮设置如下,我的故事板中有一个约束:
我在代码中链接了约束:
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myConstraint;
在键盘显示时添加了通知:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
以下是keyboardWillShow
实施:
- (void)keyboardWillShow: (NSNotification *)notification {
NSDictionary *dictionary = notification.userInfo;
CGRect keyboardFrame = [dictionary[UIKeyboardFrameEndUserInfoKey] CGRectValue];
[UIView animateWithDuration:1.0f animations:^{
self.myConstraint.constant = keyboardFrame.size.height + 18;
}];
}
虽然它有效但按钮没有动画,而是立即设置在视图上的新位置。我试图添加一个完成块来查看发生了什么,实际上是立即调用完成而不是等待它应该... ...
有什么问题?谢谢你的帮助。
答案 0 :(得分:4)
需要动画的是由约束变化触发的布局....
self.myConstraint.constant = keyboardFrame.size.height + 18;
[self.view setNeedsUpdateConstraints];
[UIView animateWithDuration:1.0f animations:^{
[self.view layoutIfNeeded];
}];
答案 1 :(得分:0)
对于您想要使用新约束值更新的public class Num<N extends Number> {
N x;
N y;
public Num(N x, N y) {
this.x = x;
this.y = y;
}
public String intValue() {
return "(" + x.intValue() + ", " + y.intValue() + ")";
}
}
,我认为您错过layoutIfNeed
。
你应该试试。
答案 2 :(得分:0)
尝试将动画延迟减少到 0.3 。键盘的速度动画比按钮的速度动画更大。
您还需要 setNeedsLayout 到您的按钮。
答案 3 :(得分:0)
如果有人在Swift 5.3中寻找相同的结果:
@IBOutlet weak var loginButtonConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
// MARK: - Functions
@objc func keyboardWillShow(notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
self.loginButtonConstraint.constant = keyboardSize.height + 20
self.view.setNeedsUpdateConstraints()
UIView.animate(withDuration: 0.2,
animations: {
self.view.layoutIfNeeded()
})
}
@objc func keyboardWillHide(notification: NSNotification) {
self.loginButtonConstraint.constant = 20
self.view.setNeedsUpdateConstraints()
UIView.animate(withDuration: 0.2,
animations: {
self.view.layoutIfNeeded()
})
}