Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christopherkarani/ff2046aac70e0c2ac25c6a9990cdde8d to your computer and use it in GitHub Desktop.
Save christopherkarani/ff2046aac70e0c2ac25c6a9990cdde8d to your computer and use it in GitHub Desktop.
UIView+SizeConstraints.Swift
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