Reputation: 57
Currently, I know how to get the current keyboard height through notifications, and I'm using that to set various auto layout constraints. When the keyboard hides, certain interface elements move down too, whilst remaining the same size. The size of this is dictated by a UITextView (and the text typed in it), except once it get's too big, scrolling is enabled and it's height is constrained to the current height (so that it doesn't immediately collapse when scrolling is enabled). This works nicely when the keyboard disappears. The problem is when the screen rotates. There's no longer room for the current fixed height, so the constraints become unsatisfiable. To properly update them and know what height the text view should be, I need to know what height the keyboard is in the orientation it's about to rotate to (since the space above it should be equal to this), is there anyway to do that without relying on hardcoded values? (which, even then probably won't work given custom keyboards)
I have considered alternatives to setting the height this way, but every solution I can think of ultimately requires the same keyboard information.
Upvotes: 0
Views: 395
Reputation: 10045
Have you considered using content insets? I usually use this, you don't have to worry about constraints at all this way, works for any descendant of UIScrollView
// Register for keyboard notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
// Process notifications
func setScrollViewInsets(insets: UIEdgeInsets) {
self.textView.contentInset = insets
self.textView.scrollIndicatorInsets = insets
}
func keyboardWillChangeFrame(note: NSNotification) {
if var kbRect = note.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue() {
let insets = UIEdgeInsets(top: 0, left: 0, bottom: kbRect.size.height, right: 0)
self.setScrollViewInsets(insets)
}
}
func keyboardWillHide(note: NSNotification) {
let insets = UIEdgeInsetsZero
self.setScrollViewInsets(insets)
}
Upvotes: 1