所以,当我尝试滚动我的UICollectionView时,我选择了一个单元格,用细橙色边框显示,当我向后滚动时,另一个单元格有边框。我读到它与细胞被重复使用有关。无论如何我在网上找到了一些代码,但是很难适应多种选择。
找到解决此问题的方法,您只需创建一个选定单元格数组并添加或删除边框
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//each cell is refreshed when page is scrolled
//Matches every cell to see if it is selected or not and adds or removes borders accordinglly
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.item];
if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]] )
{
[cell.layer setBorderColor:[UIColor orangeColor].CGColor];
cell.layer.borderWidth = 5.0f;
}
else
{
[cell.layer setBorderColor:[UIColor clearColor].CGColor];
cell.layer.borderWidth = 0.0f;
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//Adds cells indexPath to selectedCellsArray and adds border around the cell right away
NSLog(@"selected");
UICollectionViewCell*selectedCell = [collectionView cellForItemAtIndexPath:indexPath];
if (![selectedCellsArray containsObject:[NSString stringWithFormat:@"%d",indexPath.item]] ) {
[selectedCellsArray addObject:[NSString stringWithFormat:@"%d",indexPath.item]];
[selectedCell.layer setBorderColor:[UIColor orangeColor].CGColor];
selectedCell.layer.borderWidth = 5.0f;
NSLog(@"add");
}
NSLog(@"keep track of array:%@", selectedCellsArray);
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
//Removes cells indexPath from selectedCellsArray and removes border form cell right away
NSLog(@"deselected");
UICollectionViewCell*deselectedCell = [collectionView cellForItemAtIndexPath:indexPath];
if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%d",indexPath.item]] )
{
[selectedCellsArray removeObject:[NSString stringWithFormat:@"%d",indexPath.item]];
[deselectedCell.layer setBorderColor:[UIColor clearColor].CGColor];
deselectedCell.layer.borderWidth = 0.0f;
NSLog(@"remove");
}
}