【发布时间】:2016-05-27 13:22:22
【问题描述】:
为了确保表格视图中的文本字段在启用键盘的情况下始终可见,我想向上移动表格视图以防它覆盖控件。 与以编程方式应用的自动布局结合使用时,我遇到了问题。
tableview的约束定义如下:
override func viewWillLayoutSubviews() {
let views = ["tableView": tableView]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
let topConstraint = NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
self.view.addConstraint(topConstraint)
bottomConstraint = NSLayoutConstraint(item: tableView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.view.addConstraint(bottomConstraint)
}
要通过NSNotificationCenter 检测键盘,会调用以下方法(基于Getting keyboard size from userInfo in Swift 的答案):
func keyboardWillHide(sender: NSNotification) {
bottomConstraint.constant = 0.0
UIView.animateWithDuration(0.2, animations: { () -> Void in self.view.layoutIfNeeded() })
}
和
func keyboardWillShow(sender: NSNotification) {
if let userInfo = sender.userInfo {
if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
self.view.layoutIfNeeded()
bottomConstraint.constant = keyboardHeight
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
}
但是,使用此代码,约束没有正确更新。而是出现以下错误:
Unable to simultaneously satisfy constraints.
…
(
"<NSLayoutConstraint:0x109941b50 UITableView:0x1028ea600.bottom == UIView:0x10993b930.bottom>",
"<NSLayoutConstraint:0x102417290 UITableView:0x1028ea600.bottom == UIView:0x10993b930.bottom + 271>"
)
为什么约束没有更新? viewWillLayoutSubviews 是这些约束的正确位置吗?
【问题讨论】:
-
尝试从代码中删除
topConstraint。我猜它会给出约束警告。 -
topConstraint 与 bottomConstraint 无关。警告仅在我尝试更新 bottomConstraint 时出现。
标签: ios swift constraints ios-autolayout