【发布时间】:2021-02-12 05:36:40
【问题描述】:
我的每个单元格都包含一个 imageView。目标是拥有它,以便在任何时候点击或滑动单元格(或 imageView)时,图像都会随着相应的点击或滑动动画而变化。 (点击动画缩小后扩大,而滑动动画将imageView旋转180度)
起初我在我的收藏视图的didSelectItemAt 方法中设置了我的点击功能,并且效果很好。但是,当我尝试添加滑动功能时,我发现任何用户与单元格的交互都会触发相同的点击动画。
所以,现在我正在尝试在cellForItemAt 中设置点击功能。但是,由于某种原因没有调用分接选择器。任何想法为什么?
我正在使用 UICollectionViewController。 Xcode 12,快速 5。
编辑
按照@Sandeep Bhandari 的建议,我现在正在实现一个协议,以在单元格(对点击手势具有强引用)和 UICollectionViewController 之间进行通信。但是,仍然没有调用选择器。
GameTileCell
@objc protocol GameTileCellProtocol {
func didTapImageView(for cell: GameTileCell)
}
class GameTileCell: UICollectionViewCell {
// other properties
var gesture: UITapGestureRecognizer?
weak var delegate: GameTileCellProtocol?
override init(frame: CGRect) {
super.init(frame: frame)
// call configure cell method
gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
gameTileImageView.isUserInteractionEnabled = true
gameTileImageView.addGestureRecognizer(gesture!)
}
// storyboard init
// configure cell method defined
@objc func handleTap(_ sender: UITapGestureRecognizer) {
self.delegate?.didTapImageView(for: self)
print("handleTap")
}
}
UICollectionViewController
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GameTileCell.reuseID, for: indexPath) as! GameTileCell
setImageAndColor(for: cell)
cell.delegate = self
return cell
}
// other methods
extension GameTileCVC: GameTileCellProtocol {
func didTapImageView(for cell: GameTileCell) {
UIView.animate(withDuration: 0.4) {
cell.gameTileImageView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
} completion: { (_ finished: Bool) in
UIView.animate(withDuration: 0.4) {
self.setImageAndColor(for: cell)
cell.gameTileImageView.transform = CGAffineTransform.identity
}
}
print(#function)
}
}
【问题讨论】:
-
添加了新答案请检查
标签: ios swift uigesturerecognizer uicollectionviewlayout uitapgesturerecognizer