Created
February 13, 2017 09:02
-
-
Save mwrites/adbc13cd73c6b7fe6ec52e9be639efb4 to your computer and use it in GitHub Desktop.
Semi self-sizing CollectionViewCell with autolayout
This file contains hidden or 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
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