UICollectionViewDelegate 設定和專案選擇

有時,如果某個動作應該繫結到集合檢視的單元格選擇,則必須實現 UICollectionViewDelegate 協議。

假設集合檢視位於 UIViewController MyViewController 內。

Objective-C

MyViewController.h 中宣告它實現了 UICollectionViewDelegate 協議,如下所示

@interface MyViewController : UIViewController <UICollectionViewDelegate, .../* previous existing delegate, as UICollectionDataSource *>

迅速

MyViewController.swift 中新增以下內容

class MyViewController : UICollectionViewDelegate {
}

必須實現的方法是

Objective-C

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}

迅速

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
}

僅作為示例,我們可以將所選單元格的背景顏色設定為綠色。

Objective-C

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];
}

迅速

class MyViewController : UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
        cell.backgroundColor = UIColor.greenColor()
    }
}