Created
April 5, 2018 15:02
-
-
Save alsedi/64954a98bd44d1b5675002b3781f0954 to your computer and use it in GitHub Desktop.
UIView+SizeConstraints.Swift
This file contains 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 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to Swift 5