点击时,UICollectionView单元格会更改背景

use*_*271 8 objective-c ios uicollectionview

是否有可能UICollectionView仅在轻敲元素时更改背景颜色.我试过了:

-(void) collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    //change color when tapped
}

-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    //change back on touch up 
}
Run Code Online (Sandbox Code Playgroud)

但结果是,只有当我的手指保持更长时间时才能看到变化.是否有类似UITableViewCell方法的东西willSelectItemAtIndexPath:

Gui*_*gis 29

但结果是,只有当我的手指保持更长时间时才能看到变化

您遇到的延迟可能与故事板中的"延迟内容触摸"复选框有关.

故事板中的复选框

尝试取消检查.


Ste*_*olo 8

我想您可能希望保持所选单元格具有不同的背景颜色,对吧?然后尝试这段代码.

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

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor cyanColor];
}
Run Code Online (Sandbox Code Playgroud)

只需为不同状态的细胞分配不同的BG颜色即可.此外,下面的代码是序列触发方法的文档,而有人触摸collectionView单元格.您还可以在UICollectionView.h文件中找到这些文档,UICollectionViewDelegate协议部分.

// Methods for notification of selection/deselection and highlight/unhighlight events.
// The sequence of calls leading to selection from a user touch is:
//
// (when the touch begins)
// 1. -collectionView:shouldHighlightItemAtIndexPath:
// 2. -collectionView:didHighlightItemAtIndexPath:
//
// (when the touch lifts)
// 3. -collectionView:shouldSelectItemAtIndexPath: or -collectionView:shouldDeselectItemAtIndexPath:
// 4. -collectionView:didSelectItemAtIndexPath: or -collectionView:didDeselectItemAtIndexPath:
// 5. -collectionView:didUnhighlightItemAtIndexPath:
Run Code Online (Sandbox Code Playgroud)