首页 文章

选中时突出显示收集单元格

提问于
浏览
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");
}

在UICollectionViewCell内的UIImageView周围有2个空像素,所以它应该可以工作,但事实并非如此 .

它正在记录“你好”,但边框保持黑色 . 看这个截图:

enter image description here

4 回答

  • 0

    这可能对您有所帮助:

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

    你以错误的方式得到了牢房

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

    将使现在未使用的单元格出列或者分配具有指定标识符的新单元格 .

    使用

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

    代替 .

    无论如何,更清洁的解决方案是设置单元格的 backgroundViewselectedBackgroundView 属性,而不触及 backgroundProperty 颜色(默认情况下将保留 clear ) . 通过这种方式,您可以避免委托方法并实现相同的行为 .

  • 0

    做一个 reloadItemsAtIndexPaths :然后在cellForItemAtIndexPath中检查是否 [[collectionView indexPathsForSelectedItems] containsObject:indexPath] 如果为true,则更改单元格的属性 .

  • 12
    • 此代码可帮助您更改所选单元格的背景颜色
    -(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
    }
    

相关问题