簡體   English   中英

觀察UICollectionView中選定單元格的數量

[英]Observing number of selected cells in UICollectionView

我想使用KVO在UICollectionView中選定單元格的數量更改時得到通知。 當我嘗試UICollectionView子類並添加新的屬性nSelectedCells時,嘗試添加更新nSelectedCells的邏輯時遇到了問題。 所選單元格數量過多的地方可能會發生變化:

  • 以編程方式-視圖: deselectItemAtIndexPathselectItemAtIndexPathreloadData ,...
  • didDeselectItemAtIndexPath控制器: didDeselectItemAtIndexPathdidSelectItemAtIndexPath
  • 更多?

跟蹤此值的最佳方法是什么。 最好從UICollectionView子類中。

UICollectionViewCell具有selected屬性。 您可以覆蓋此方法的setter,因為當更改單元格的選擇狀態時,這是唯一保證被調用的方法。

也許將具有屬性的UICollectionView子類UICollectionView ,以保留所選單元格的計數器,並根據單元格是選中還是取消選中,在setSelected:注冊由UICollectionViewCell子類觸發的通知。

請注意,僅因為setSelected:被調用並不意味着選擇狀態已更改。

- (void)setSelected:(BOOL)selected {
    if (super.selected != selected) {
        if (selected) {
            // cell was unselected and became selected, increase counter
        } else {
            // cell was selected and become unselected, decrease counter
        }
    }
    super.selected = selected;
}

使用NSMutableSet跟蹤選定單元格的索引路徑,當選擇一個單元格時,添加其indexPath進行設置; 取消選擇單元格,從集合中刪除其索引路徑。

僅當用戶成功選擇/取消選擇集合視圖中的項目時,集合視圖才會調用這些方法。 以編程方式設置選擇/取消選擇時,它不會調用該方法。

@property (nonatomic) NSMutableSet *selectedCellIndexPathsSet;

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //do some things.
    [self.selectedCellIndexPathsSet addObject:indexPath];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //do some thing.
    [self.selectedCellIndexPathsSet removeObject:indexPath];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM