2013-06-20 9 views
8

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 
} 

しかし結果は私が少し長い時間のために私の指を保つときだけ変更を見ることができます。 UITableViewCellメソッドwillSelectItemAtIndexPath:のようなものがありますか?

答えて

28

しかし、結果は少し長い時間のために私は私の指を維持する場合にのみ、私は変化を見ることができるということです

あなたが経験している遅延が多分に「遅延コンテンツタッチ」チェックボックスに関連していますストーリーボード。

the checkbox in storyboard

未チェックし、それをしてみてください。

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: 

+0

私はUICollectionViewとテーブルビューの組み合わせビューにカスタムグリッドを変えた...この答えを探していました。両方のメソッドを実装すると、選択を選択してから変更することができます。ありがとうスティーブ、これは私のためのトリックでした。 –

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

このメソッドは、コレクションビューをスクロールしても機能しません。再使用された細胞も着色します。 –

+0

[この回答](http://stackoverflow.com/a/34503118/3681880)と上記の質問のように、 'didHighlightItemAtIndexPath'と' didUnhighlightItemAtIndexPath'を使うべきです。 – Suragch