需求:
1.默認(rèn)選中第一個cell
2.選中和沒被選中的cell都有不同的背景圖片。
實(shí)現(xiàn)步驟
- 第一步,實(shí)現(xiàn)默認(rèn)選中第一個cell:
注意:一定要在UICollectionView加載完數(shù)據(jù)之后設(shè)置默認(rèn)選中第一個cell
// 在我的項(xiàng)目中,我在網(wǎng)絡(luò)加載完UICollectionView的數(shù)據(jù)之后寫了以下幾行代碼
[self.collectionView reloadData];
// 設(shè)置默認(rèn)選中第一個cell
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:kNilOptions];
- 第二步,在
UICollectionViewDataSource
代理方法中
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
FKNetworkCardCvCell *cell = (FKNetworkCardCvCell *)[collectionView dequeueReusableCellWithReuseIdentifier:networkCardCellId forIndexPath:indexPath];
// 這方法里面主要就是設(shè)置選中和沒選中時,cell的背景圖片
[self updateCellStatus:cell selected:cell.isSelected];
return cell;
}
- 第三步,在
UICollectionViewDelegate
代理方法中
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
// 該cell networkCardCvCell已被選中
FKNetworkCardCvCell *networkCardCvCell = (FKNetworkCardCvCell *)[collectionView cellForItemAtIndexPath:indexPath];
[self updateCellStatus:networkCardCvCell selected:networkCardCvCell.selected];
}
// 該方法在你不選中某個cell的時候調(diào)用
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
// 該cell networkCardCvCell已被撤銷選中
FKNetworkCardCvCell *networkCardCvCell = (FKNetworkCardCvCell *)[collectionView cellForItemAtIndexPath:indexPath];
[self updateCellStatus:networkCardCvCell selected:networkCardCvCell.selected];
}
總結(jié)
實(shí)現(xiàn)這個需求的方法有多種,但是筆者覺得這種做法是比較好的。省得寫什么輔助屬性。如果你有更好的方法,求分享哦!