Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Last active February 7, 2018 00:57
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarshilShah/6d75593d4c78a8015f54a090b115a40b to your computer and use it in GitHub Desktop.
Save HarshilShah/6d75593d4c78a8015f54a090b115a40b to your computer and use it in GitHub Desktop.
Fallbacks and syntactic sugar for iOS 11 safeArea API
//
// UIView+SafeAnchors.swift
//
extension UIView {
var safeTopAnchor: NSLayoutYAxisAnchor { return optionalSafeAreaLayoutGuide?.topAnchor ?? topAnchor }
var safeBottomAnchor: NSLayoutYAxisAnchor { return optionalSafeAreaLayoutGuide?.bottomAnchor ?? bottomAnchor }
var safeLeftAnchor: NSLayoutXAxisAnchor { return optionalSafeAreaLayoutGuide?.leftAnchor ?? leftAnchor }
var safeRightAnchor: NSLayoutXAxisAnchor { return optionalSafeAreaLayoutGuide?.rightAnchor ?? rightAnchor }
var safeLeadingAnchor: NSLayoutXAxisAnchor { return optionalSafeAreaLayoutGuide?.leadingAnchor ?? leadingAnchor }
var safeTrailingAnchor: NSLayoutXAxisAnchor { return optionalSafeAreaLayoutGuide?.trailingAnchor ?? trailingAnchor }
var safeCenterXAnchor: NSLayoutXAxisAnchor { return optionalSafeAreaLayoutGuide?.centerXAnchor ?? centerXAnchor }
var safeCenterYAnchor: NSLayoutYAxisAnchor { return optionalSafeAreaLayoutGuide?.centerYAnchor ?? centerYAnchor }
var safeWidthAnchor: NSLayoutDimension { return optionalSafeAreaLayoutGuide?.widthAnchor ?? widthAnchor }
var safeHeightAnchor: NSLayoutDimension { return optionalSafeAreaLayoutGuide?.heightAnchor ?? heightAnchor }
private var optionalSafeAreaLayoutGuide: UILayoutGuide? {
if #available(iOS 11, *) {
return safeAreaLayoutGuide
} else {
return nil
}
}
}
@iamsimranjot
Copy link

You could return layoutMarginsGuide in the else part.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment