2013-04-07 92 views
0

我想突出顯示UICollectionView中帶有黃色邊框的選定集合單元格,以便用戶可以看到當前選中的單元格。我嘗試這樣做:選中時突出顯示收集單元格

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    FilterCell *filterCell = (FilterCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"FilterCell" forIndexPath:indexPath]; 
    filterCell.window.backgroundColor = [UIColor yellowColor]; 
    filterCell.backgroundColor = [UIColor yellowColor]; 

    NSLog(@"hello"); 
} 

大約有2個UIImageView的空像素內UICollectionViewCell所以它應該工作,但事實並非如此。

它正在記錄「你好」,但邊界保持黑色。看到這個截圖:

enter image description here

回答

12

你所得到的細胞以錯誤的方式

FilterCell *filterCell = (FilterCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"FilterCell" forIndexPath:indexPath]; 

將出列,這是不正確的使用現在的小區或分配一個新的用指定的標識符。

使用

FilterCell *filterCell = (FilterCell *)[collectionView cellForItemAtIndexPath:indexPath]; 

代替。

反正一個清潔的解決方案是設置該單元的backgroundViewselectedBackgroundView性能,而不觸及backgroundProperty色(即會留clear作爲默認值)。通過這種方式,您可以避免委託方法並實現相同的行爲。

+0

HMM的背景色。這是一個很好的答案。我無法決定我是否喜歡它比我的更好。將有興趣看看別人的想法。在我最後的收集視圖中,我改變了選定單元的大小,這有利於我的方法,我認爲;另一方面,這個想法更直接,更直接地涉及OP的問題。 – danh 2013-04-07 18:33:46

+1

如果您更改單元格的大小,則會調整'backgroundView'和'selectedBackgroundView'的大小。在統一的顏色背景視圖的情況下,這種方法一切都很好;) – 2013-04-07 18:36:24

+0

是啊?我相信。 +1。 :-) – danh 2013-04-07 18:38:12

1

做一個reloadItemsAtIndexPaths:在那裏,然後在cellForItemAtIndexPath,檢查是否[[collectionView indexPathsForSelectedItems] containsObject:indexPath]如果爲true,那麼在那裏更改單元格的屬性。

+0

嗨,爲可見細胞做這項工作嗎?如果單元格可見,我試圖分配一個圖像: if([[collectionView indexPathsForVisibleItems] containsObject:indexPath]){ imageView.image = [gridImages objectAtIndex:indexPath.row]; } 但它不工作。這種情況從來都不是真的。 – 2013-07-11 10:58:57

+1

它應該適用於任何選擇。 NSLog將您的indexPath和indexPathsForVisibleItems(都可以在格式字符串中用%@看到)。 – danh 2013-07-11 14:04:17

0

這可能會幫助您:

cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"YOUR_FILE_NAME.png"]]; 
0

- 這個代碼可以幫助你改變所選單元格

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath]; 

if (cell.selected) { 
cell.backgroundColor = [UIColor blueColor]; // highlight selection 
} 
else 
{ 
cell.backgroundColor = [UIColor redColor]; // Default color 
} 
return cell; 
} 

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { 

UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath]; 
datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection 
} 
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath]; 
datasetCell.backgroundColor = [UIColor redColor]; // Default color 
} 
相關問題