Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to user touches for UICollectionViewCell in iOS?

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

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

But I don't know how to add touch listener for each 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.

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

like image 222
malhobayyeb Avatar asked Oct 20 '14 06:10

malhobayyeb


2 Answers

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

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    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 :)

like image 73
mustafa Avatar answered Oct 25 '22 21:10

mustafa


Swift 5

didSelectItemAtIndexPath has been renamed to didSelectItemAt in Swift 5

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

    }
like image 32
babatunde adewole Avatar answered Oct 25 '22 22:10

babatunde adewole