如何在 iOS 中监听 UICollectionViewCell 的用户触摸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26459668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:15:42  来源:igfitidea点击:

How to listen to user touches for UICollectionViewCell in iOS?

iosswiftuicollectionviewuicollectionviewcell

提问by malhobayyeb

I have implemented a UICollectionViewthat holds list of UIImageView objects.

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

I want the user to be taken to YouTube with specific URL when he touched an image.

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

But I don't know how to add touch listener for each UICollectionViewCell:

但我不知道如何为每个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
    }

My PhotoCell class has a member variable that holds the URL to youtube.

我的 PhotoCell 类有一个成员变量,用于保存指向 youtube 的 URL。

For each PhotoCell object, when pressed, I want my app to send the user to youtube.com website or APP (if installed)

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

回答by mustafa

You should implement UICollectionViewDelegateprotocol method collectionView(_:didSelectItemAtIndexPath:). When you press one of your collection view cells this method get called. Here is sample implementation

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

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

By the way I don't know where you get url. So I improvised a bit :)

顺便说一下,我不知道你从哪里得到 url。所以我即兴了一点:)