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)
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 :)
Swift 5
didSelectItemAtIndexPath has been renamed to didSelectItemAt in Swift 5
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//Do your logic here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With