2013-06-20 28 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和TableView中組合視圖。實現這兩種方法允許選擇並且然後改變選擇。謝謝史蒂夫,這對我來說是個訣竅。 –

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

應該在[this Answer](http://stackoverflow.com/a/34503118/3681880)和上面的問題中使用'didHighlightItemAtIndexPath'和'didUnhighlightItemAtIndexPath'。 – Suragch