Created
November 6, 2021 07:02
-
-
Save aaronlab/73bd74db0eb160292a1644bf7bbf45c3 to your computer and use it in GitHub Desktop.
Swift Safe Area Inset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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