To assure that textfields in a tabular view are always visible with a keyboard enabled, I want to shift the tableview upwards in case it would cover the controls. I have problems to do this in combination with autolayout applied programmatically.
The constraints for the tableview are defined as follows:
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)
}
To detect the keyboard via NSNotificationCenter
the following methods are called (based on an answer at 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() })
}
And
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()
})
}
}
}
However, with this the code the constraints are not updated correctly. Instead, the following error appears:
Unable to simultaneously satisfy constraints.
…
(
"<NSLayoutConstraint:0x109941b50 UITableView:0x1028ea600.bottom == UIView:0x10993b930.bottom>",
"<NSLayoutConstraint:0x102417290 UITableView:0x1028ea600.bottom == UIView:0x10993b930.bottom + 271>"
)
Why are the constraints not updated? Is viewWillLayoutSubviews
the correct location for these constraints?