我已经在NSArray中创建了图像,如viewDidLoad中所示。
menuImgs = @[@"image1", @"image2", @"image3", @"image4"];
并在UICollectionView中应用上面的图像,如下所示。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeCell" forIndexPath:indexPath];
UIImage *iconImg = [UIImage imageNamed:menuImgs[arrayCountChecker]];
UIImageView *cellImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:menuImgs[arrayCountChecker]]];
cellImage.frame = CGRectMake(cellWidth/2-iconImg.size.width,cellHeight/2-iconImg.size.height, iconImg.size.width, iconImg.size.height);
[cell addSubview:cellImage];
return cell;
}
我想要的是我想在此功能中点击特定的UICollectionViewCell时更改图像颜色。
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
答案 0 :(得分:0)
如果您只想更改所选单元格的背景颜色,请使用cell.selectedBackgroundView,否则
初始化一个数组并在该数组中存储选定的索引。并且当collectionview加载数据时从数组检查索引并根据更改图像颜色。当有人选择新单元格从数组中删除旧索引并存储新单元格并重新加载colloectionview时。这是代码示例。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
cell.lblFilter.text = filterTitles[indexPath.row];
cell.imgvFilter.image = filterImages[indexPath.row];
if([indexPath isEqual:selectedIndexPath])
{
cell.imgvFilter.superview.layer.borderColor = [UIColor lightBlue].CGColor;
cell.lblFilter.textColor = [UIColor lightBlue];
}
else
{
cell.lblFilter.textColor = [UIColor textGray];
cell.imgvFilter.superview.layer.borderColor = [UIColor borderGray].CGColor;
}
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[collvFilter scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
if (![indexPath isEqual:selectedIndexPath])
{
NSIndexPath *indexPathToReload = selectedIndexPath;
selectedIndexPath = indexPath;
[collvFilter reloadItemsAtIndexPaths:@[indexPathToReload, indexPath]];
}
}