Dismiss The Keyboard When Scrolling a ScrollView
Daily Coding Tip 220
I’m sorry for the absence of Daily Coding Tips for the last few weeks.
In November my dad died and I lost my job, so it was hard to stay motivated and inspired to write these tutorials.
I will do my best to get back to the regular schedule from today onwards.
In iOS 16 it is possible to dismiss the on-screen keyboard just by scrolling in a ScrollView. There are multiple ‘modes’ for how this behavior is presented.
Here’s Apple’s documentation describes them:
automaticDetermine the mode automatically based on the surrounding context.
immediatelyDismiss the keyboard as soon as scrolling starts.
interactivelyEnable people to interactively dismiss the keyboard as part of the scroll operation.
neverNever dismiss the keyboard automatically as a result of scrolling.
I found interactively to work pretty erratically. Scrolling away from the TextField had no effect, but scrolling back up from the bottom caused the keyboard to be dismissed. I’m going to use immediately, because this has an obvious definition and seems to work well.
My ScrollView has two instances of Text in it, one which prompts the user to scroll up and another indicating that the bottom of the ScrollView has been reached. The ‘swipe up’ Text has a height of 500, allowing the text to be centered vertically. The ‘bottom’ Text has 500 padding above it, pushing the Text down to the bottom of the ScrollView where it belongs.
If you can’t see the on-screen keyboard and you’re using the Simulator, press Cmd + K or click I/O > Keyboard > Toggle Software Keyboard to display it.
Here’s how it should look:



