Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Created November 6, 2021 07:02
Show Gist options
  • Save aaronlab/73bd74db0eb160292a1644bf7bbf45c3 to your computer and use it in GitHub Desktop.
Save aaronlab/73bd74db0eb160292a1644bf7bbf45c3 to your computer and use it in GitHub Desktop.
Swift Safe Area Inset
//
// UIApplication+Ext.swift
// BottomSheetExample
//
// Created by Aaron Lee on 2021/11/06.
//
import UIKit
extension UIApplication {
var safeAreaInsets: UIEdgeInsets {
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
guard let safeArea = window?.safeAreaInsets else { return .zero }
return safeArea
}
if #available(iOS 13.0, *) {
let window = UIApplication.shared.windows.first
guard let safeArea = window?.safeAreaInsets else { return .zero }
return safeArea
}
if #available(iOS 15.0, *) {
let window = UIApplication.shared.connectedScenes
.filter { $0.activationState == .foregroundActive }
.first(where: { $0 is UIWindowScene })
.flatMap { $0 as? UIWindowScene }?.windows
.first(where: \.isKeyWindow)
guard let safeArea = window?.safeAreaInsets else { return .zero }
return safeArea
}
return .zero
}
var safeAreaTopInset: CGFloat {
return safeAreaInsets.top
}
var safeAreaBottomInset: CGFloat {
return safeAreaInsets.bottom
}
var safeAreaLeftInset: CGFloat {
return safeAreaInsets.left
}
var safeAreaRightInset: CGFloat {
return safeAreaInsets.right
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment