【问题标题】:How to listen to user touches for UICollectionViewCell in iOS?如何在 iOS 中监听用户对 UICollectionViewCell 的触摸?
【发布时间】:2025-12-23 22:05:11
【问题描述】:

我已经实现了一个 UICollectionView,它包含 UIImageView 对象的列表。

我希望用户在触摸图片时被带到具有特定 URL 的 YouTube。

但我不知道如何为每个 UICollectionViewCell 添加触摸监听器:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    var cell: PhotoCell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoCell", forIndexPath: indexPath) as PhotoCell
    cell.loadImage(thumbnailFileURLs[indexPath.row], originalImagePath: originalFileURLs[indexPath.row])

    return cell
    }

我的 PhotoCell 类有一个成员变量保存 youtube 的 URL。

对于每个 PhotoCell 对象,当按下时,我希望我的应用将用户发送到 youtube.com 网站或 APP(如果已安装)

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell


    【解决方案1】:

    你应该实现UICollectionViewDelegate协议方法collectionView(_:didSelectItemAtIndexPath:)。当您按下其中一个集合视图单元格时,将调用此方法。这是示例实现

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let url = thumbnailFileURLS[indexPath.item]
        if UIApplication.sharedApplication().canOpenURL(url) {
            UIApplication.sharedApplication().openURL(url)
        }
    }
    

    顺便说一句,我不知道你从哪里得到网址。所以我即兴创作了一点:)

    【讨论】:

    • 顺便问一下indexPath.item和indexPath.row有什么区别
    • 没有区别。它是语义的。当你与UITableViews 打交道时,你说“行”,当你与UICollectionViews 打交道时,你说“项目”
    • 这是否进入 viewDidLoad()
    • @tccpg288 不,它在 viewDidLoad() 下面作为视图控制器中的一个单独函数
    【解决方案2】:

    斯威夫特 5

    didSelectItemAtIndexPath 在 Swift 5 中已重命名为 didSelectItemAt

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
             //Do your logic here
    
        }
    

    【讨论】: