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()
    }
}