点击集合视图单元格时我需要动画。我为它编写了一个覆盖函数。但是当我在自定义单元格上覆盖
UICollectionView didSelectItemAt
时,touchesBegan
不起作用。
视图控制器
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.answersCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
self.selectedIndex = indexPath.item
}
自定义单元格类
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.5) {
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.1) {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.1) {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
我想为选择设置动画。
您写道“当点击集合视图单元格时我需要动画......”。如果这是您唯一的要求,我会这样做:
确保您的集合视图允许选择,如下所示:
myCollectionView.allowsSelection = true
向您的 CustomCell 添加一个函数,如下所示:
class CustomCellClass: UICollectionViewCell {
//configure the cell as you normally would
/// animates cell after a selection
func animateSelection() {
//please note that this is the most basic way of animating
//there are multiple other ways. check out the provided link below in the post
UIView.animate(withDuration: 0.5) {
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
} completion: { _ in
UIView.animate(withDuration: 0.1) {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
}
}
在
didSelectItemAt
回调期间调用这个新函数。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//you don't need to do this - the cell is already selected
//self.answersCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
if let selectedCell = collectionView.cellForItem(at: indexPath) as? CustomCellClass {
selectedCell.animateSelection()
}
//do other things you need to do in order to react to cell selection
..
}
这里是交流,大家可以参考看看其他动画技巧