Skip to content

Instantly share code, notes, and snippets.

@JoeMatt
Forked from bizz84/UIViewAutoLayoutAnchors.swift
Last active September 26, 2018 22:58
Show Gist options
  • Save JoeMatt/da65ed4f601437d543d117d6017bfbda to your computer and use it in GitHub Desktop.
Save JoeMatt/da65ed4f601437d543d117d6017bfbda to your computer and use it in GitHub Desktop.
UIView extension for programmatic Auto Layout
import UIKit
extension UIView {
enum SALViewError : Error {
case noSuperview
}
func anchorAllEdgesToSuperview() throws {
guard let superview = superview else { throw SALViewError.noSuperview }
self.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 9.0, *) {
addSuperviewConstraint(constraint: topAnchor.constraint(equalTo: superview.topAnchor))
addSuperviewConstraint(constraint: leftAnchor.constraint(equalTo: superview.leftAnchor))
addSuperviewConstraint(constraint: bottomAnchor.constraint(equalTo: superview.bottomAnchor))
addSuperviewConstraint(constraint: rightAnchor.constraint(equalTo: superview.rightAnchor))
}
else {
for attribute : NSLayoutConstraint.Attribute in [.left, .top, .right, .bottom] {
anchorToSuperview(attribute: attribute)
}
}
}
func anchorToSuperview(attribute: NSLayoutConstraint.Attribute) {
addSuperviewConstraint(constraint: NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: superview, attribute: attribute, multiplier: 1.0, constant: 0.0))
}
func addSuperviewConstraint(constraint: NSLayoutConstraint) {
superview?.addConstraint(constraint)
}
}
class ViewController {
@IBOutlet var offlineView: UIView!
@IBAction func showView(sender: UIButton) {
self.view.addSubview(offlineView)
offlineView.anchorAllEdgesToSuperview()
}
}
@JoeMatt
Copy link
Author

JoeMatt commented Sep 26, 2018

Updated for XCode 10 Swift 4.2

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