在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