UIButton返回动画失效求助:键盘收起时按钮无法复位
我来帮你搞定这个问题~你的按钮在键盘弹出时动画正常,但收起时没反应,核心原因是每次调用animateSendButton都创建了新的底部约束,旧约束还在生效,导致Auto Layout冲突,系统忽略了新的约束修改。下面是具体的修复方案:
步骤1:保留底部约束的引用
首先在你的ViewController里声明一个属性,用来存储SendButton的底部约束,这样我们可以直接修改它的constant值,而不是每次创建新约束:
private var sendButtonBottomConstraint: NSLayoutConstraint!
步骤2:初始化时绑定约束到属性
修改setupSendButton方法,把底部约束赋值给我们刚声明的属性,而不是直接激活匿名约束:
func setupSendButton() { self.view.addSubview(sendButton) sendButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true sendButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true sendButton.heightAnchor.constraint(equalToConstant: 60).isActive = true // 把底部约束赋值给属性并激活 sendButtonBottomConstraint = sendButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) sendButtonBottomConstraint.isActive = true sendButton.translatesAutoresizingMaskIntoConstraints = false }
步骤3:修改动画函数,直接更新约束的constant
原来的animateSendButton每次创建新约束是错误的,现在改成直接修改已有的约束值:
func animateSendButton(bottomConstraint: CGFloat) { // 直接修改约束的constant sendButtonBottomConstraint.constant = bottomConstraint UIView.animate(withDuration: 0.55, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: { self.view.layoutIfNeeded() }, completion: nil) }
额外检查:确保TextView的Delegate已设置
别忘了在viewDidLoad里给textView设置delegate,不然textViewDidEndEditing可能不会被触发:
override func viewDidLoad() { super.viewDidLoad() setupSendButton() dismissKeyboard() // 添加这行代码 textView.delegate = self }
这样修改后,当你收起键盘时,textViewDidEndEditing会调用动画函数,修改底部约束的constant值,再触发布局动画,按钮就能平滑回到底部了~
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

