Skip to content

Instantly share code, notes, and snippets.

@yccheok
Created March 5, 2024 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yccheok/06b9d717a614a3e4f4398859d5a9a1ac to your computer and use it in GitHub Desktop.
Save yccheok/06b9d717a614a3e4f4398859d5a9a1ac to your computer and use it in GitHub Desktop.
class ShopCollectionViewCell: UICollectionViewCell {
...
func collapse() {
zeroHeightConstraint.isActive = true
}
func expand() {
zeroHeightConstraint.isActive = false
}
}
extension ShopViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item = indexPath.item
self.selectedShop = shops[item]
for i in (0..<isExpanded.count) {
if i == item {
// ensure always visible
isExpanded[i] = true
} else {
// set all other rows to false
isExpanded[i] = false
}
if let shopCollectionViewCell = collectionView.cellForItem(at: IndexPath(item: i, section: 0)) as? ShopCollectionViewCell {
if isExpanded[i] {
shopCollectionViewCell.expand()
shopCollectionViewCell.select()
} else {
shopCollectionViewCell.collapse()
shopCollectionViewCell.unselect()
}
}
}
updateButtons(selectedShop)
UIView.animate(withDuration: Constants.config_shortAnimTime, animations: {
collectionView.performBatchUpdates(nil, completion: { [weak self] _ in
guard let self = self else { return }
let minY = collectionView.contentOffset.y
let maxY = collectionView.bounds.height + minY
if let attribute = collectionView.layoutAttributesForItem(at: indexPath) {
let rectMinY = attribute.frame.minY
let rectMaxY = attribute.frame.maxY + self.PADDING
if rectMinY < minY {
self.ensureSelectedRowViewStaysAtTheTop()
} else if rectMaxY > maxY {
let cgPoint = CGPoint(
x: collectionView.contentOffset.x,
y: collectionView.contentOffset.y + (rectMaxY - maxY)
)
collectionView.setContentOffset(cgPoint, animated: true)
}
}
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment