我想更改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。我该如何解决这个问题?
答案 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
删除该方法