Last active
April 10, 2019 14:51
-
-
Save bizz84/6cb3555e7f34f63a3ae9 to your computer and use it in GitHub Desktop.
UIView extension for programmatic Auto Layout
This file contains 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
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) | |
} | |
} |
This file contains 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
class ViewController { | |
@IBOutlet var offlineView: UIView! | |
@IBAction func showView(sender: UIButton) { | |
self.view.addSubview(offlineView) | |
offlineView.anchorAllEdgesToSuperview() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.