Skip to content

Instantly share code, notes, and snippets.

@evil159
Created March 6, 2019 08:29
Show Gist options
  • Save evil159/79780f7d1eafa9b9aacea420112420c8 to your computer and use it in GitHub Desktop.
Save evil159/79780f7d1eafa9b9aacea420112420c8 to your computer and use it in GitHub Desktop.
A base cell that works with MagazineLayout for nib based cells.
open class SizeableCollectionViewCell: UICollectionViewCell {
private var widthConstraint: NSLayoutConstraint!
public override init(frame: CGRect) {
super.init(frame: frame)
contentView.translatesAutoresizingMaskIntoConstraints = false
let bottomConstraint = bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
bottomConstraint.priority = .required - 1
NSLayoutConstraint.activate(
[
leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
topAnchor.constraint(equalTo: contentView.topAnchor),
bottomConstraint
]
)
widthConstraint = widthAnchor.constraint(equalToConstant: bounds.width)
widthConstraint.priority = .required - 1
widthConstraint.isActive = true
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
contentView.translatesAutoresizingMaskIntoConstraints = false
let bottomConstraint = bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
bottomConstraint.priority = .required - 1
NSLayoutConstraint.activate(
[
leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
topAnchor.constraint(equalTo: contentView.topAnchor),
bottomConstraint
]
)
widthConstraint = widthAnchor.constraint(equalToConstant: bounds.width)
widthConstraint.priority = .required - 1
widthConstraint.isActive = true
}
override open func preferredLayoutAttributesFitting(
_ layoutAttributes: UICollectionViewLayoutAttributes)
-> UICollectionViewLayoutAttributes
{
guard let attributes = layoutAttributes as? MagazineLayoutCollectionViewLayoutAttributes else {
assertionFailure("`layoutAttributes` must be an instance of `MagazineLayoutCollectionViewLayoutAttributes`")
return super.preferredLayoutAttributesFitting(layoutAttributes)
}
let size: CGSize
if attributes.shouldVerticallySelfSize {
widthConstraint.constant = layoutAttributes.size.width
size = super.preferredLayoutAttributesFitting(layoutAttributes).size
} else {
// No self-sizing is required; respect whatever size the layout determined.
size = layoutAttributes.size
}
layoutAttributes.size = size
return layoutAttributes
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment