I have a search bar text field and a table view (for google auto complete) that I would like to translate up when the keyboard comes into view. I am successfully doing this, however, I am getting warnings/errors about my constraints. I am using auto layout via storyboard on this view and tried to disable/enable the constraints prior to/after showing/hiding the keyboard, but I am still getting these errors. Am I not disabling auto layout correctly? I followed what was given in this SO response.
override func viewDidLoad() {
...
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
...
}
func keyboardWillShow(sender: NSNotification) {
self.pixieLabel.hidden = true
self.searchBar.setTranslatesAutoresizingMaskIntoConstraints(true)
self.startingTableView.setTranslatesAutoresizingMaskIntoConstraints(true)
self.searchBar.frame.origin.y -= 150
self.startingTableView.frame.origin.y -= 150
}
func keyboardWillHide(sender: NSNotification) {
self.pixieLabel.hidden = false
self.searchBar.setTranslatesAutoresizingMaskIntoConstraints(false)
self.startingTableView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.searchBar.frame.origin.y += 150
self.startingTableView.frame.origin.y += 150
}
Solution Code
func keyboardWillShow(sender: NSNotification) {
self.pixieLabel.hidden = true
self.seachBarTopConstraint.constant -= 150
self.searchBar.layoutIfNeeded()
}
func keyboardWillHide(sender: NSNotification) {
self.pixieLabel.hidden = false
self.seachBarTopConstraint.constant += 150
self.searchBar.layoutIfNeeded()
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…