Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chosa91/d37baa75f7d21f79681f9d9c3eeeb749 to your computer and use it in GitHub Desktop.
Save chosa91/d37baa75f7d21f79681f9d9c3eeeb749 to your computer and use it in GitHub Desktop.
Avoid the keyboard by leveraging additionalSafeAreaInsets.
// Avoids the keyboard in a UIKit app by leveraging additionalSafeAreaInsets.
// You can put this in the root view controller so the whole app will avoid the keyboard.
// Only tested on iOS 13.3.
// Made for https://douglashill.co/reading-app/
@objc func updateSafeAreaForKeyboardFromNotification(_ notification: Notification) {
guard let endFrameInScreenCoords = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
return
}
// Please consider whether the force unwrap here is safe for your own use case.
let endFrameInSelfCoords = self.view.convert(endFrameInScreenCoords, from: self.view.window!.screen.coordinateSpace)
// Need to clear the additionalSafeAreaInsets in order to be able to read the unaltered safeAreaInsets. We’ll set it again just below.
self.additionalSafeAreaInsets = .zero
let safeBounds = self.view.bounds.inset(by: self.view.safeAreaInsets)
let isDocked = endFrameInSelfCoords.maxY >= safeBounds.maxY
let keyboardOverlapWithViewFromBottom = isDocked ? max(0, safeBounds.maxY - endFrameInSelfCoords.minY) : 0
self.additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardOverlapWithViewFromBottom, right: 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment