Skip to content

Instantly share code, notes, and snippets.

@bizz84
Last active April 10, 2019 14:51
Show Gist options
  • Save bizz84/6cb3555e7f34f63a3ae9 to your computer and use it in GitHub Desktop.
Save bizz84/6cb3555e7f34f63a3ae9 to your computer and use it in GitHub Desktop.
UIView extension for programmatic Auto Layout
import UIKit
extension UIView {
func anchorAllEdgesToSuperview() {
self.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 9.0, *) {
addSuperviewConstraint(topAnchor.constraintEqualToAnchor(superview?.topAnchor))
addSuperviewConstraint(leftAnchor.constraintEqualToAnchor(superview?.leftAnchor))
addSuperviewConstraint(bottomAnchor.constraintEqualToAnchor(superview?.bottomAnchor))
addSuperviewConstraint(rightAnchor.constraintEqualToAnchor(superview?.rightAnchor))
}
else {
for attribute : NSLayoutAttribute in [.Left, .Top, .Right, .Bottom] {
anchorToSuperview(attribute)
}
}
}
func anchorToSuperview(attribute: NSLayoutAttribute) {
addSuperviewConstraint(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()
}
}
@bizz84
Copy link
Author

bizz84 commented Jul 16, 2015

This code works with iOS 6.0 or above.
The NSLayoutConstraint API can be entirely replaced with the new constraintEqualToAnchor methods if iOS 9.0 or above is used.

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