Skip to content

Instantly share code, notes, and snippets.

@JaviSoto
Last active April 14, 2020 11:55
Show Gist options
  • Save JaviSoto/4058336e0a3f16c9d1d6600c81de4483 to your computer and use it in GitHub Desktop.
Save JaviSoto/4058336e0a3f16c9d1d6600c81de4483 to your computer and use it in GitHub Desktop.
Status-bar agnostic UIView.safeAreaInsets API
extension UIView {
/// Convenience API to query iOS 11's `UIView.safeAreaInsets`'s insets (also known as "#NotEmbraceTheNotch")
/// in a backwards compatible API.
/// It also differs slightly from `UIView.safeAreaInsets` in that it only takes the "Notch" into account
/// and not the status bar. This allows you to inset content so that the notch doesn't clip it, but you can still
/// lay it out below the status bar.
/// Note: This won't be as versitile as the UIKit version because it won't take into account things like navigation bars,
/// but it should be correct for views in "full-screen" view controllers, where the UIKit `safeAreaInsets` API falls short.
var twSafeAreaInsets: UIEdgeInsets {
guard #available(iOS 11.0, *) else {
return .zero
}
guard let window = self.window else {
return .zero
}
/// We use the window because it only takes the notch into account, and not the status bar.
let windowSafeAreaInsets = window.safeAreaInsets
let viewFrameInWindowCoordinateSystem = self.convert(self.bounds, to: window)
return UIEdgeInsets(
top: viewFrameInWindowCoordinateSystem.minY < windowSafeAreaInsets.top ? windowSafeAreaInsets.top - viewFrameInWindowCoordinateSystem.minY : 0,
left: viewFrameInWindowCoordinateSystem.minX < windowSafeAreaInsets.left ? windowSafeAreaInsets.left - viewFrameInWindowCoordinateSystem.minX : 0,
bottom: viewFrameInWindowCoordinateSystem.maxY > window.frame.height - windowSafeAreaInsets.bottom ? viewFrameInWindowCoordinateSystem.maxY - window.frame.height + windowSafeAreaInsets.bottom : 0,
right: viewFrameInWindowCoordinateSystem.maxX > window.frame.width - windowSafeAreaInsets.right ? viewFrameInWindowCoordinateSystem.maxX - window.frame.width + windowSafeAreaInsets.right : 0
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment