iOS UICollectionView更改所选项目的颜色

时间:2016-11-24 09:45:04

标签: ios objective-c

我想更改UICollectionView中所选项目的颜色,未选中的项目也应该具有默认颜色。但有时会选择两个以上的项目,有时甚至没有。

我的代码是:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell;
    StanderdScoreCardPlayerCollectionViewCell * standardScoreCardPlayerCollectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StanderdScoreCardPlayerCollectionViewCell" forIndexPath:indexPath];

    if(standardScoreCardPlayerCollectionViewCell.selected || selectedPlayerIndex == indexPath.row){
        standardScoreCardPlayerCollectionViewCell.outerView.backgroundColor = NAV_BAR_BARTINT_COLOR_GREEN;
    }
    else{
        standardScoreCardPlayerCollectionViewCell.outerView.backgroundColor = UIColorFromRGB(0xC9C9C9);
    }

    cell = standardScoreCardPlayerCollectionViewCell;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView       didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView cellForItemAtIndexPath:indexPath];
    StanderdScoreCardPlayerCollectionViewCell * cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.outerView.backgroundColor = NAV_BAR_BARTINT_COLOR_GREEN;
    selectedPlayerIndex = indexPath.row;
    [self displayDataWithPlayer:selectedPlayerIndex andHole:selectedHoleIndex];
}

- (void) collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    StanderdScoreCardPlayerCollectionViewCell * cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.outerView.backgroundColor = UIColorFromRGB(0xC9C9C9);
}

selectedPlayerIndex始终指向所选的玩家,并在viewDidLoad中声明为1。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

试试这个,改变你的cellForItemAtIndexPath就像这样

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell;

    StanderdScoreCardPlayerCollectionViewCell * standardScoreCardPlayerCollectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StanderdScoreCardPlayerCollectionViewCell" forIndexPath:indexPath];


    if(selectedPlayerIndex == indexPath.row)
    {
        standardScoreCardPlayerCollectionViewCell.outerView.backgroundColor = NAV_BAR_BARTINT_COLOR_GREEN;
    }
    else
    {
        standardScoreCardPlayerCollectionViewCell.outerView.backgroundColor = UIColorFromRGB(0xC9C9C9);
    }

    cell = standardScoreCardPlayerCollectionViewCell;
}
return cell;
}

didSelectItemAtIndexPath喜欢这个

- (void)collectionView:(UICollectionView *)collectionView       didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    selectedPlayerIndex = indexPath.row;

    [self displayDataWithPlayer:selectedPlayerIndex andHole:selectedHoleIndex];

    [collectionView reloadData];
}

也无需实施didDeselectItemAtIndexPath删除该方法