My ViewController view contains scrollView with bounds of it's superview and there is a tableView at the bottom of the scrollView as it's subview. TableView height constraint is set to it's content size height and above it there is textfield. So when the user touches textField keyboard appears. And in order to the textField could be visible I want to scroll the scrollView up, but usually there is not enough space so I want to increase the tableView height. And the problem is that it behaves like first the scrollView is scrolled and later the tableViewConstraint
is set so it never scrolls enough when there is no space. Could I 'dispatch'
tableViewConstraint.constant = keyboardHeight
in some way that it will be executed first on UI.
override func viewDidLoad() {
tableViewConstraint.constant = TableView.contentSize.height
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
...
}
@objc func keyboardWillShow(notification:NSNotification){
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
tableViewConstraint.constant = keyboardHeight
let boundsOfOffsetView = scrollView.bounds.offsetBy(dx: CGFloat(0), dy: keyboardHeight)
scrollView.scrollRectToVisible(boundsOfOffsetView, animated: true)
}
}
You can do your layout changes in an animate(withDuration:animations:completion:)
block and call layoutIfNeeded()
to force the changes to occur at the time of your choosing. I would try something like this to start:
// Within your if statement…
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
UIView.animate(withDuration: 1.0/3.0) {
tableViewConstraint.constant = keyboardHeight
scrollView.layoutIfNeeded()
}
let boundsOfOffsetView = scrollView.bounds.offsetBy(dx: CGFloat(0), dy: keyboardHeight)
scrollView.scrollRectToVisible(boundsOfOffsetView, animated: true)