swift - UITapGestureRecognizer 不改变 CollectionViewCell 的内容。 swift

标签 swift uicollectionview uicollectionviewcell

我有一个包含许多不同图片的 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 ,您可以将其作为senderview 进行访问:

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/

相关文章:

node.js - 解析服务器电话登录 - 该用户名的帐户已存在

ios - 识别 subview

ios - CollectionViewCell 匹配数据时无法正常工作

swift - UICollectionView 不重绘

ios - 快速获取collectionView中心单元格的indexPath?

ios - 使用 PagedView 时如何将 CollectionViewCell 的边缘固定到 CollectionView

ios - AFNetworking 的 UICollectionView 异步下载错误

ios - 收到推送通知时使用协议(protocol)更新 UIViewController?

swift - AVAudioPlayer 在 Swift 4.2 中产生延迟

ios - 自定义 UICollectionViewFlowLayout