Skip to content

Instantly share code, notes, and snippets.

@alsedi
Created April 5, 2018 15:02
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alsedi/64954a98bd44d1b5675002b3781f0954 to your computer and use it in GitHub Desktop.
Save alsedi/64954a98bd44d1b5675002b3781f0954 to your computer and use it in GitHub Desktop.
UIView+SizeConstraints.Swift
import Foundation
extension UIView {
func height(constant: CGFloat) {
setConstraint(value: constant, attribute: .height)
}
func width(constant: CGFloat) {
setConstraint(value: constant, attribute: .width)
}
private func removeConstraint(attribute: NSLayoutAttribute) {
constraints.forEach {
if $0.firstAttribute == attribute {
removeConstraint($0)
}
}
}
private func setConstraint(value: CGFloat, attribute: NSLayoutAttribute) {
removeConstraint(attribute: attribute)
let constraint =
NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: value)
self.addConstraint(constraint)
}
}
@abhishekbedi1432
Copy link

Updated to Swift 5

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