NEW: Master Swift design patterns with my latest book! >>

How to adjust a UIScrollView to fit the keyboard

Written by Paul Hudson    @twostraws

If your user interface brings up the keyboard, you should respond by adjusting your layout so that all parts are still visible. If you're using a UIScrollView or any classes that have a scroll view as part of their layout (table views and text views, for example), this means adjusting the contentInset property to account for the keyboard.

First you need to register for keyboard change notifications. Put this into your viewDidLoad() method:

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: Notification.Name.UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)

Now add this method somewhere else in your class:

@objc func adjustForKeyboard(notification: Notification) {
    let userInfo = notification.userInfo!

    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)

    if notification.name == Notification.Name.UIKeyboardWillHide {
        yourTextView.contentInset = UIEdgeInsets.zero
    } else {
        yourTextView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
    }

    yourTextView.scrollIndicatorInsets = yourTextView.contentInset

    let selectedRange = yourTextView.selectedRange
    yourTextView.scrollRangeToVisible(selectedRange)
}

That example code is for adjusting text views. If you want it to apply to a regular scroll view, just take out the last two lines - they are in there so that the text view readjusts itself so the user doesn't lose their place while editing.

Available from iOS 2.0 – see Hacking with Swift tutorial 16

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Need to know Objective-C fast?

I wrote a book dedicated to teaching Objective-C to developers who already know Swift – it's the fastest way to get up to speed!

Click here to visit the Hacking with Swift store >>