[英]Observing number of selected cells in UICollectionView
我想使用KVO在UICollectionView中選定單元格的數量更改時得到通知。 當我嘗試UICollectionView
子類並添加新的屬性nSelectedCells
時,嘗試添加更新nSelectedCells
的邏輯時遇到了問題。 所選單元格數量過多的地方可能會發生變化:
deselectItemAtIndexPath
, selectItemAtIndexPath
, reloadData
,... didDeselectItemAtIndexPath
控制器: didDeselectItemAtIndexPath
, didSelectItemAtIndexPath
跟蹤此值的最佳方法是什么。 最好從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.