Skip to content

Instantly share code, notes, and snippets.

@earltedly
Last active August 29, 2015 14:25
Show Gist options
  • Save earltedly/879201d6e4c2e6ce48f2 to your computer and use it in GitHub Desktop.
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
// In a UICollectionViewCell
@IBOutlet weak var leftStatConstraint: NSLayoutConstraint!
leftStatConstraint = leftStatConstraint.reapplyToView(self.contentView, multiplier: leftMultiplier)
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