iOS-UICollectionView cell設(shè)置背景圖片

需求:

1.默認(rèn)選中第一個(gè)cell
2.選中和沒被選中的cell都有不同的背景圖片。

實(shí)現(xiàn)步驟

  • 第一步,實(shí)現(xiàn)默認(rèn)選中第一個(gè)cell:
    注意:一定要在UICollectionView加載完數(shù)據(jù)之后設(shè)置默認(rèn)選中第一個(gè)cell
// 在我的項(xiàng)目中,我在網(wǎng)絡(luò)加載完UICollectionView的數(shù)據(jù)之后寫了以下幾行代碼
[self.collectionView reloadData];
            
// 設(shè)置默認(rèn)選中第一個(gè)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è)置選中和沒選中時(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];

}

// 該方法在你不選中某個(gè)cell的時(shí)候調(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)這個(gè)需求的方法有多種,但是筆者覺得這種做法是比較好的。省得寫什么輔助屬性。如果你有更好的方法,求分享哦!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容