Last active
May 4, 2017 14:41
-
-
Save mosluce/01eabc9355425d8249d743f59b40cb2e to your computer and use it in GitHub Desktop.
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 { | |
| @discardableResult func constraint(attribute attr1: NSLayoutAttribute, relatedBy: NSLayoutRelation = .equal, toItem: Any? = nil, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint { | |
| self.translatesAutoresizingMaskIntoConstraints = false | |
| let attr = attr2 ?? attr1 | |
| return NSLayoutConstraint(item: self, attribute: attr1, relatedBy: relatedBy, toItem: toItem, attribute: attr, multiplier: multiplier, constant: constant) | |
| } | |
| @discardableResult func edge(insets: UIEdgeInsets, toItem: Any) -> [NSLayoutConstraint] { | |
| return [ | |
| constraint(attribute: .top, toItem: toItem, constant: insets.top), | |
| constraint(attribute: .left, toItem: toItem, constant: insets.left), | |
| constraint(attribute: .right, toItem: toItem, constant: -insets.right), | |
| constraint(attribute: .bottom, toItem: toItem, constant: -insets.bottom) | |
| ] | |
| } | |
| @discardableResult func edge(offset: CGFloat, toItem: Any) -> [NSLayoutConstraint] { | |
| return edge(insets: UIEdgeInsets(top: offset, left: offset, bottom: offset, right: offset), toItem: toItem) | |
| } | |
| } | |
| // Example | |
| let view = UIView() | |
| let a = UIView() | |
| view.addSubview(a) | |
| ([ | |
| a.constraint(attribute: .width, constant: 200), | |
| a.constraint(attribute: .height, constant: 40), | |
| a.constraint(attribute: .centerX, toItem: view), | |
| a.constraint(attribute: .centerY, toItem: view) | |
| ] + a.edge(offset: 16, toItem: view)).forEach { (c) in | |
| c.isActive = true | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment