Last active
August 29, 2015 14:25
-
-
Save earltedly/879201d6e4c2e6ce48f2 to your computer and use it in GitHub Desktop.
Swift extension to recreate a NSLayoutConstraint with a new multiplier and replace it
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
// In a UICollectionViewCell | |
@IBOutlet weak var leftStatConstraint: NSLayoutConstraint! | |
leftStatConstraint = leftStatConstraint.reapplyToView(self.contentView, multiplier: leftMultiplier) |
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
extension NSLayoutConstraint { | |
/** | |
Allows the copying of a layout constraint, just modifying the multiplier | |
:param: multiplier the new multiplier to use | |
:returns: the new layout constraint | |
*/ | |
public func copyWithMultiplier(multiplier: CGFloat) -> NSLayoutConstraint { | |
let duplicate = NSLayoutConstraint(item: self.firstItem, | |
attribute: self.firstAttribute, | |
relatedBy: self.relation, | |
toItem: self.secondItem, | |
attribute: self.secondAttribute, | |
multiplier: multiplier, | |
constant: self.constant) | |
duplicate.identifier = self.identifier | |
return duplicate | |
} | |
/** | |
Forms a new constraint with the specified multiplier. Disables the current one, | |
applies the new one to the specified view and returns it. | |
:param: view the view to apply the new constraint to | |
:param: multiplier the multiplier | |
:returns: the newly formed constraint (disgard the original) | |
*/ | |
func reapplyToView(view: UIView, multiplier: CGFloat) -> NSLayoutConstraint { | |
if multiplier == self.multiplier { | |
return self | |
} | |
let newConstraint = self.copyWithMultiplier(multiplier) | |
self.active = false | |
view.addConstraint(newConstraint) | |
return newConstraint | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment