How to adjust your scrollview for the keyboard in swift 3+

Viewed 5236

How do you adjust your scrollview to compensate for a keyboard vertically? Read on...

Yes I know this is some basic info, but I randomly noticed today that all of the answers I saw about this topic are all over the place with info, versions and/or use bangs all over the place... but nothing solid for Swift 3+.

2 Answers

A modification to make it work on iOS 11 is to use UIKeyboardFrameEndUserInfoKey rather than UIKeyboardFrameBeginUserInfoKey. Just a simplified approach to @crewshin's solution:

@objc func keyboardWillShow(_ notification: NSNotification) {                
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        scrollView.contentInset.bottom = keyboardSize.height
    }
}

@objc func keyboardWillHide(_ notification: NSNotification) {        
    scrollView.contentInset.bottom = 0
}
Related