Skip to content

Instantly share code, notes, and snippets.

@mwrites
Created February 13, 2017 09:02
Show Gist options
  • Save mwrites/adbc13cd73c6b7fe6ec52e9be639efb4 to your computer and use it in GitHub Desktop.
Save mwrites/adbc13cd73c6b7fe6ec52e9be639efb4 to your computer and use it in GitHub Desktop.
Semi self-sizing CollectionViewCell with autolayout
var COLLECTIONVIEWHEIGHT: CGFloat!
var LINESPACING: CGFloat!
var cachedHeights = [String:CGFloat]()
class WordTileCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var wordLabel: UILabel!
var identifier: String!
var word: String = "" {
didSet {
wordLabel.text = word
}
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let toReturn = super.preferredLayoutAttributesFitting(layoutAttributes)
if identifier == "WordCell3" {
let totalHeight = cachedHeights.values.reduce(0, +)
let finalHeight = COLLECTIONVIEWHEIGHT - totalHeight
let newFrame = toReturn
newFrame.frame = CGRect(x: toReturn.frame.minX, y: toReturn.frame.minY, width: toReturn.frame.width, height: finalHeight)
newFrame.bounds = CGRect(x: 0, y: 0, width: toReturn.frame.width, height: finalHeight)
return newFrame
} else {
cachedHeights[identifier] = toReturn.bounds.height + LINESPACING
}
return toReturn
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment