UICollectionViewCell单选

时间:2014-11-13 10:25:17

标签: ios xcode uicollectionview uicollectionviewcell

有些人可以用uicollectionview指导我,我将边框颜色设置为单元格,现在我的要求是当我点击单元格时它的边框颜色将是红色,现在我点击第二个单元格现在第二个单元格边框将是红色和第一个细胞边界将是清晰的颜色。

UICollectionViewCell *selectedCell =
[collectionView cellForItemAtIndexPath:indexPath];

selectedCell.contentView.backgroundColor = nil;
[selectedCell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
[selectedCell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
[selectedCell.contentView.layer setBorderWidth:3.0f];

const NSTimeInterval kAnimationDuration = 0.20;
[UIView animateWithDuration:kAnimationDuration animations:^{
    [selectedCell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
    selectedCell.alpha = 0.0f;
} completion:^(BOOL finished) {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        [selectedCell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
        selectedCell.alpha = 1.0f;
    }];
}];

2 个答案:

答案 0 :(得分:2)

我得到了解决方案。

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

UICollectionViewCell *selectedCell =
[collectionView cellForItemAtIndexPath:indexPath];

selectedCell.contentView.backgroundColor = nil;
[selectedCell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
[selectedCell.contentView.layer setBorderWidth:3.0f];   
}

并添加此委托方法

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *deselectedCell =
[collectionView cellForItemAtIndexPath:indexPath];
deselectedCell.contentView.backgroundColor = nil;
[deselectedCell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
[deselectedCell.contentView.layer setBorderWidth:3.0f];
}

答案 1 :(得分:0)

使用didSelectItemAtIndexPath并保存所选单元格的IndexPath。这是我的代码,我正在使用你所要求的相同的东西。只需替换..

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCell *selectedCell = (ProductCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [selectedCell setBackgroundColor:[UIColor redColor]];

    if (self.selectedIndexPath)
    {
        ProductCell *deselectedCell = (ProductCell *)[collectionView cellForItemAtIndexPath:self.selectedIndexPath];
        [deselectedCell setBackgroundColor:[UIColor clearColor]];
    }

    self.selectedIndexPath = indexPath;
}