【发布时间】:2020-10-02 21:13:18
【问题描述】:
我有一个表视图,我在 viewDidLoad() 方法中使用 4 个约束进行了初始化。我想稍后在代码中以编程方式更改 bottomAnchor,所以我将其保存为变量 bottomAnchor 然后我有另一个变量 keyboardBottomAnchor 用于更改的约束
这些是初始约束:
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
bottomAnchor = tableViewe.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: (-1) * card.cardHandleAreaHeight + -20)
bottomAnchor.isActive = true
基本上,我希望表格视图在键盘打开时上升,在键盘关闭时返回。看起来是这样的:
@objc func keyboardAppears(notification: Notification) {
let userInfo = notification.userInfo
keyboardFrame = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
//this is the original constraint
self.bottomConstraint.isActive = false
//Here I make a new variable to save the new constraint
keyboardBottomConstraint = tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -1 * keyboardFrame.height)
keyboardBottomConstraint.isActive = true
}
@objc func keyboardDisappears(notification: Notification) {
NSLayoutConstraint.deactivate([keyboardBottomConstraint])
bottomConstraint.isActive = true
}
keyboardAppears 方法正在工作(当键盘显示时,表格视图会上升)但keyboardDisappears 方法给我一个Unable to simultaneously satisfy constraints 错误(也就是说bottomConstraint 和keyboardBottomConstraint 都是主动)
对为什么会发生这种情况有任何想法吗?
更新:
我使用了下面的.constant(这有效,但仅在我第一次打开键盘时)
@objc func keyboardAppears(notification: Notification) {
let userInfo = notification.userInfo
var keyboardFrame = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
bottomConstraint.constant = -1 * keyboardFrame.height
tableView.scrollUp()
}
@objc func keyboardDisappears(notification: Notification) {
returnOriginalConstraint()
}
func returnOriginalConstraint() {
bottomAnchor.constant = (-1) * buttonCard.cardHandleAreaHeight + -20
}
//scrolling method
func scrollUp() {
DispatchQueue.main.async {
self.entrySpace.scrollToRow(at: IndexPath(row: self.data.count - 1, section: 0), at: .top, animated: true)
}
}
【问题讨论】:
-
不需要创建新的约束。只需更新您已有的约束的
constant属性。您可以为这种变化设置动画。 -
感谢部分帮助:) 现在,它仅在我第一次使键盘出现/消失时起作用,但第二次不起作用。知道为什么吗?
-
当键盘消失的时候你有没有把常数设回去?如果没有看到您的新代码,我不能再说什么。您正在观察哪些通知?您是否设置了断点或日志语句以查看正在调用的函数?
-
不是您问题的答案,但如果您想避免使用键盘,我建议您使用IHKeyboardAvoiding
-
我在帖子中添加了带有常量的代码,如前所述,这仅在第一次有效?另外,我正在观察
keyboardWillHideNotification和keyboardWillShowNotification
标签: ios swift xcode uikit nslayoutconstraint