Forked from bizz84/UIViewAutoLayoutAnchors.swift
Last active
September 26, 2018 22:58
-
-
Save JoeMatt/da65ed4f601437d543d117d6017bfbda to your computer and use it in GitHub Desktop.
UIView extension for programmatic Auto Layout
This file contains hidden or 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 { | |
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) | |
} | |
} |
This file contains hidden or 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
Updated for XCode 10 Swift 4.2