我有一个包含许多不同图片的 Collection View ,我希望当点击图片时,它周围会出现一个边框。
我制作了一个自定义单元格和一个 UICollectionViewCell,其中 imageView 嵌入到图片的另一个 View (即轮廓)中。因此,我设置了一个 UITapGestureRecognizer 来获取索引,但是当我将外部 View 设置为具有边界时,它不起作用。
这是我的手机:
import UIKit
class PicViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageOutline: UIView!
}
这是在我的 UICollectionViewController 中:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell
// Configure the cell
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
cell.imageOutline.addGestureRecognizer(tapGesture)
return cell
这是点击手势的方法
func handleTap(sender: UITapGestureRecognizer) {
print("tap")
if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {
let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell
cell.imageOutline.layer.borderWidth = 5
} else {
print("")
}
}
最佳答案
在您的 handleTap
例程中,您调用了错误的方法来检索单元格。你要cellForItem(at:)
如果它不在屏幕上,它将检索现有单元格或返回 nil
:
let cell = collectionView?.cellForItem(at: indexPath) as! PicViewCell
替代解决方案
如果您正在修改正在点击的 View ,您可以将其作为sender
的view
进行访问:
func handleTap(sender: UITapGestureRecognizer) {
if let imageOutline = sender.view as? UIImageView {
imageOutline.layer.borderWidth = 5
}
}
注意:在这两种解决方案中,您应该在单元格勾勒出轮廓时更新您的模型,这样如果该单元格滚出屏幕然后又回到屏幕上,您可以使用该模型数据来设置在覆盖 collectionView(_:cellForItemAt:)
时正确地显示单元格的轮廓。
关于swift - UITapGestureRecognizer 不改变 CollectionViewCell 的内容。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358064/