iOS UICollectionViewCell点击改变背景图片

方法一:在控制器里面进行修改:

代理方法:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DiscoverRechangeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DiscoverRechangeCenterCell" forIndexPath:indexPath];
cell.discoverRechangeCenterModel = self.sourceArr[indexPath.row];
//默认选中效果
if (indexPath == self.selectIndexPath) {
cell.backgroundImgV.hidden = NO;
} else {
cell.backgroundImgV.hidden = YES;
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
DiscoverRechangeCenterCell *cell = (DiscoverRechangeCenterCell *)[collectionView cellForItemAtIndexPath:indexPath];
//选中之后的cell变颜色
[self updateCellStatus:cell selected:NO];
self.selectIndexPath = indexPath;
[collectionView reloadData];
}
//取消选中操作
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
DiscoverRechangeCenterCell *cell = (DiscoverRechangeCenterCell *)[collectionView cellForItemAtIndexPath:indexPath];
[self updateCellStatus:cell selected:YES];
}
// 改变cell的背景图片
-(void)updateCellStatus:(DiscoverRechangeCenterCell *)cell selected:(BOOL)selected{
cell.backgroundImgV.hidden = selected;
}

方法二:在UICollectionViewCell中重写select方法实现

UICollectionViewCell中:
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
if (selected) {
self.backgroundImgV.hidden = NO;
} else {
self.backgroundImgV.hidden = YES;
}
}
控制器中:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DiscoverRechangeCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DiscoverRechangeCenterCell" forIndexPath:indexPath];
cell.discoverRechangeCenterModel = self.sourceArr[indexPath.row];
//默认选中效果
if (indexPath == self.selectIndexPath) {
cell.backgroundImgV.hidden = NO;
} else {
cell.backgroundImgV.hidden = YES;
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
DiscoverRechangeCenterCell *cell = (DiscoverRechangeCenterCell *)[collectionView cellForItemAtIndexPath:indexPath];
self.selectIndexPath = indexPath;
[cell setSelected:YES];
[collectionView reloadData];
}
特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!
技术狗 » iOS UICollectionViewCell点击改变背景图片