I have an collectionView. I'm increasing it's height on selction. But, I want add animation on increasing height.
How do I achieve in sizeForItemAt method.
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
if let selectedRow = selectedRow {
if selectedRow == indexPath.item {
return NSSize(width: collectionView.bounds.width, height: 572)
}
}
return NSSize(width: collectionView.bounds.width, height: 71)
}
Here a complete code for the func. I scale x and y by a factor of 1.5, bring to front over other cells and keep the size at the end:
And on deselect, reset the original size
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set) {
for indexPath in indexPaths { // { .first {
if self.selectedRow != nil && self.selectedRow! == indexPath.item {
self.selectedRow = nil
} else {
self.selectedRow = indexPath.item
}
if let cell = collectionView.item(at: indexPath.item) {
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.duration = 2.0
animation.fromValue = 1.0
animation.toValue = 1.5
cell.view.layer!.zPosition = 1
cell.view.layer?.add(animation, forKey: "transform.scale")
cell.view.layer?.setAffineTransform( CGAffineTransform(scaleX: 1.5, y: 1.5)) //<<--- NEW CODE
CATransaction.commit()
}
}
}
func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set) {
for indexPath in indexPaths {
let theItem = indexPath.item
if let cell = collectionView.item(at: theItem) {
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.duration = 1.0
animation.fromValue = 1.5
animation.toValue = 1.0
cell.view.layer!.zPosition = -1
cell.view.layer?.add(animation, forKey: "transform.scale")
cell.view.layer?.setAffineTransform( CGAffineTransform(scaleX: 1, y: 1))
CATransaction.commit()
}
}
}