在UICollectionView
中,我有一個自定義UICollectionViewCellClass
,其中prepareForReuse被默認格式化工作人員覆蓋。重複使用單元格UICollectionView - 某些單元格未被選中
我有一個NSMutableArray
包含NSIndexPaths
從didSelectItemAtIndexPath:。
cellForItemAtIndexPath:我重新格式化選定的單元格,使它們顯示爲選中狀態。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
ButtonCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ButtonCell" forIndexPath:indexPath];
NSString *title = self.ingredientsBook.names[indexPath.item];
cell.label.text = title;
if ([self isSelectedIndexPath:indexPath]){
cell.backgroundColor = [UIColor whiteColor];
cell.label.textColor = [UIColor blueColor];
}
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
self.searchButton.enabled = YES;
ButtonCell *cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];
[selectedCellIndexPaths addObject:indexPath];
NSLog(@"%@", selectedCellIndexPaths);
cell.backgroundColor = [UIColor whiteColor];
cell.label.textColor = [UIColor blueColor];
NSString *name = self.ingredientsBook.names[indexPath.item];
[self.selectedIngredientNames addObject:name];
}
問題是,當我點擊第一個單元格時,不可能選擇第16或第17個。 或者如果我點擊前三個,不可能選擇最後三個。 didSelectItemAtIndexPath
沒有被稱爲我想。
我覺得它必須是非常簡單的東西,但我現在看不到它。
我試圖把NSLogs
放在shouldSelectItemAtIndexPath
中,以瞭解該方法是否被調用並且該方法根本沒有被調用。發生這種情況時,所選一個與有問題的單元之間的距離爲16個單元。
這裏有其他數據源的方法和isSelectedIndexPath:
-(BOOL)isSelectedIndexPath:(NSIndexPath *)indexPath{
for (NSIndexPath *test in selectedCellIndexPaths){
if (test == indexPath){
return YES;
}
}
return NO;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [self.ingredientsBook.names count];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%@", indexPath);
return YES;
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
self.searchButton.enabled = ([[collectionView indexPathsForSelectedItems] count] > 0);
ButtonCell *cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor blackColor];
cell.label.textColor = [UIColor whiteColor];
[selectedCellIndexPaths removeObject:indexPath];
NSString *name = self.ingredientsBook.names[indexPath.item];
[self.selectedIngredientNames removeObject:name];
}
什麼是isSelectedIndexPath?你在哪裏創建它?如果[self isSelectedIndexPath:indexPath]返回false,我認爲你還需要一個「else」部分來說明單元格應該是什麼樣子。 – rdelmar 2013-04-06 15:59:57
它是一種檢查indexPath是否包含在NSIndexPaths的NSMutableArray中的方法。當indexPath等於數組中的某一個時,它總是返回false。 – ragnarok 2013-04-06 16:36:53
好的,你是否在if語句中添加了「else」部分以查看是否有幫助。由於單元重用,如果if語句爲false,則需要將單元格的外觀設置爲未選中狀態。 – rdelmar 2013-04-06 16:45:25