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

时间:2022-04-22 23:59:41

I have implemented a UICollectionView that holds list of UIImageView objects.

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

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

我希望用户在触摸图片时使用特定的网址访问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网站或APP(如果已安装)

1 个解决方案

#1


31  

You should implement UICollectionViewDelegate protocol 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 :)

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

#1


31  

You should implement UICollectionViewDelegate protocol 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 :)

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