Skip to content

Instantly share code, notes, and snippets.

extension UIViewController {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return view.safeAreaLayoutGuide.topAnchor
} else {
return topLayoutGuide.bottomAnchor
}
}
var safeBottomAnchor: NSLayoutYAxisAnchor {
extension UIView {
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return safeAreaLayoutGuide.topAnchor
} else {
return 0
}
}
var safeBottomAnchor: NSLayoutYAxisAnchor {
extension UIViewController {
var compatibleSafeInsets: UIEdgeInsets {
if #available(iOS 11, *) {
return view.safeAreaInsets
} else {
return UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0)
}
}
}
// in your UIViewController
func setupMySubview() {
let topInset = compatibleSafeInsets.top
let bottomInset = compatibleSafeInsets.bottom
let leftInset = compatibleSafeInsets.left
let rightInset = compatibleSafeInsets.right
let height = view.frame.size.height - bottomInset - topInset
let width = view.frame.size.width - leftInset - rightInset
myButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, multiplier: 1.0)