2

선택한 셀을 강조 표시하거나 색칠하는 코드가 포함 된 가로 컬렉션 뷰가 있습니다. 선택한 셀을 강조 표시 한 다음 5 셀마다 강조 표시됩니다. 무슨 일이 일어나고 있는지 아십니까?UICollectionViewCell 선택 셀 5 개를 선택/강조 표시

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    for(int x = 0; x < [cellArray count]; x++){ 
     UICollectionViewCell *UnSelectedCell = [cellArray objectAtIndex:x]; 
     UnSelectedCell.backgroundColor = [UIColor colorWithRed:0.2 green:0.5 blue:0.8 alpha:0.0]; 
    } 
    UICollectionViewCell *SelectedCell = [cellArray objectAtIndex:indexPath.row]; 
    SelectedCell.backgroundColor = [UIColor colorWithRed:0.2 green:0.5 blue:0.8 alpha:1.0]; 
    cellSelected = indexPath.row; 
    NSLog(@"%i", cellSelected); 

} 

답변

6

스크롤 할 때 셀이 이 다시 사용 되었기 때문에 이러한 현상이 발생합니다. 모델의 모든 행 (예 : 배열 또는 NSMutableIndexSet)의 "강조 표시된"상태를 저장하고 collectionView:cellForItemAtIndexPath:에 해당 행의 상태에 따라 셀의 배경색을 설정해야합니다.

didSelectItemAtIndexPath에서 새로 선택된 과 이전에 선택한 셀의 색을 설정하는 것으로 충분합니다.

업데이트 :하나 셀을 한 번에 선택할 수 있다면, 당신은 단지 선택된 셀의 인덱스 경로를 기억해야합니다. 이전의 세포 unhighlight, didSelectItemAtIndexPath에서

@property (strong, nonatomic) NSIndexPath *selectedIndexPath; 

을하고, 새로운 셀 강조 :

현재 강조 표시된 행에 대해 속성 selectedIndexPath를 선언 cellForItemAtIndexPath에서

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (self.selectedIndexPath != nil) { 
     // deselect previously selected cell 
     UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:self.selectedIndexPath]; 
     if (cell != nil) { 
      // set default color for cell 
     } 
    } 
    // Select newly selected cell: 
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; 
    if (cell != nil) { 
     // set highlight color for cell 
    } 
    // Remember selection: 
    self.selectedIndexPath = indexPath; 
} 

을 올바른 배경 색상을 사용 :

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Identifier" forIndexPath:indexPath]; 
    if ([self.selectedIndexPath isEqual:indexPath) { 
     // set highlight color 
    } else { 
     // set default color 
    } 
} 
+0

재사용 할 수있는 세포로 인해 발생하지만, 나는 당신을 잃어 버렸습니다. 강조 표시된 상태는 어떻게 저장해야합니까? didSelectItemAtIndexPath에서? 마지막 문장에서 무엇을 의미합니까? – Spenciefy

+0

@Spenciefy :'collectionView : cellForItemAtIndexPath :'가 호출 될 때마다, 셀의 정확한 배경색을 설정해야합니다. 따라서 모든 행 *에 대한 상태를 "기억"해야합니다. 그것이 어레이 또는 인덱스 세트에 상태를 저장하는 것을 의미합니다. –

+0

알겠습니다. 그렇다면 인덱스 세트에서 선택되거나 선택되지 않은 것을 어떻게 할당합니까? – Spenciefy

0

콜렉션에는 재사용 가능한 셀을 사용하는 것이 좋다고 생각합니다. 셀을 재사용하기 전에 셸에서 기본 배경색을 설정하십시오.

+0

그는 재사용 셀 이전에 기본값을가집니다. 셀을 선택하면 강조 표시됩니다. – Spenciefy