Forked from alsedi/gist:64954a98bd44d1b5675002b3781f0954
Last active
December 10, 2018 14:12
-
-
Save christopherkarani/ff2046aac70e0c2ac25c6a9990cdde8d to your computer and use it in GitHub Desktop.
UIView+SizeConstraints.Swift
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
extension UIView { | |
func height(constant: CGFloat) { | |
setConstraint(value: constant, attribute: .height) | |
} | |
func width(constant: CGFloat) { | |
setConstraint(value: constant, attribute: .width) | |
} | |
private func removeConstraint(attribute: NSLayoutConstraint.Attribute) { | |
constraints.forEach { | |
if $0.firstAttribute == attribute { | |
removeConstraint($0) | |
} | |
} | |
} | |
private func setConstraint(value: CGFloat, attribute: NSLayoutConstraint.Attribute) { | |
removeConstraint(attribute: attribute) | |
let constraint = | |
NSLayoutConstraint(item: self, | |
attribute: attribute, | |
relatedBy: NSLayoutConstraint.Relation.equal, | |
toItem: nil, | |
attribute: NSLayoutConstraint.Attribute.notAnAttribute, | |
multiplier: 1, | |
constant: value) | |
self.addConstraint(constraint) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment