2014-10-20 73 views
8

我已經實現了一個保存UIImageView對象列表的UICollectionView如何在iOS中偵聽用戶觸摸UICollectionViewCell?

我想讓用戶在觸摸圖片時帶上特定的URL。

但我不知道如何添加觸摸監聽每個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 
    } 

我的光電類有保存URL到YouTube的成員變量。

對於每個光電對象,按下時,我想我的應用程序給用戶發送到youtube.com網站或APP(如果已安裝)

回答

28

你應該實現UICollectionViewDelegate協議方法collectionView(_:didSelectItemAtIndexPath:)。當您按下其中一個集合視圖單元格時,會調用此方法。這裏是樣本實施

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

順便說一句,我不知道你在哪裏得到的網址。所以我即興創作了一下:)

+0

順便問一下,indexPath.item和indexPath.row有什麼區別 – malhobayyeb 2014-10-20 07:05:14

+2

沒有什麼區別。它是語義的。當你處理'UITableView's時,你會說「行」,當你處理'UICollectionView's喲說「項目」 – mustafa 2014-10-20 07:06:32

+0

這是否在viewDidLoad() – tccpg288 2017-03-26 01:31:50