Spe*_*efy 2 xcode objective-c ios uicollectionview 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);
}
Run Code Online (Sandbox Code Playgroud)
这是因为滚动时会重复使用单元格.您必须为模型中的所有行存储"突出显示"状态(例如,在数组或中NSMutableIndexSet),并collectionView:cellForItemAtIndexPath:根据该行的状态设置单元格的背景颜色.
在didSelectItemAtIndexPath它中应该足以设置新选择的和先前选择的单元格的颜色.
更新:如果一次只能选择一个单元格,则只需记住所选单元格的索引路径.
声明selectedIndexPath当前突出显示的行的属性:
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
Run Code Online (Sandbox Code Playgroud)
在didSelectItemAtIndexPath,取消突出显示上一个单元格,并突出显示新单元格:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
在cellForItemAtIndexPath,使用正确的背景颜色:
- (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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2195 次 |
| 最近记录: |