8

是否有可能UICollectionView仅在点击元素时更改背景颜色。我努力了:

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

-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    //change back on touch up 
}

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

4

3 回答 3

29

但结果是,只有当我的手指稍长一点时,我才能看到变化

您遇到的延迟可能与情节提要中的“延迟内容触摸”复选框有关。

故事板中的复选框

尝试取消选中它。

于 2013-07-01T15:27:42.107 回答
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];
}

只需简单地为不同状态的单元格分配不同的 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:

于 2014-02-25T08:15:57.487 回答
3
// In Swift    
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
  let cell = collectionView.cellForItemAtIndexPath(indexPath) as! UICollectionViewCell
  cell.backgroundColor = UIColor.magentaColor()
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
  let cell = collectionView.cellForItemAtIndexPath(indexPath) as! UICollectionViewCell
  cell.backgroundColor = UIColor.cyanColor()
}
于 2015-06-09T20:26:28.480 回答