DataSource:
extension AuthorDataSource: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: content[indexPath.row].identifier, for: indexPath)
switch content[indexPath.item] {
case .authorImage:
return CGSize(width: collectionView.frame.width, height: 275)
case .expandable:
let cell = cell as! ExpandableCollectionViewCell
/// Fetch height of `cell. authDescLabel` here
if cell.isExpanded {
return CGSize(width: collectionView.frame.width, height: 500)
} else {
return CGSize(width: collectionView.frame.width, height: 200)
}
}
}
}
extension AuthorDataSource: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? ExpandableCollectionViewCell else { return }
cell.configureWhenExpanded()
/// collectionView.reloadItems(at: [indexPath]) here, `sizeForItemAt` would be called but reset isExpanded to false . . .
}
}
Function in custom cell:
class ExpandableCollectionViewCell: UICollectionViewCell {
var isExpanded: Bool = false
func configureWhenExpanded() {
isExpanded = !isExpanded
if isExpanded {
authorDescLabel.numberOfLines = 0
authorDescLabel.lineBreakMode = .byWordWrapping
readMoreSeeLessAttrText = "See less"
} else {
authorDescLabel.numberOfLines = 6
authorDescLabel.lineBreakMode = .byTruncatingTail
readMoreSeeLessAttrText = "Read More"
}
}
}