-2

在我的集合视图中允许多项选择。

当我点击一个项目时,系统会自动选择一个不可见的项目。

这是我的代码:

-(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;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView 
       didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.searchButton.enabled = YES;

    ButtonCell *cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.label.textColor = [UIColor blueColor];

    NSString *name = self.ingredientsBook.names[indexPath.item];
    [self.selectedIngredientNames addObject:name];
}

有什么建议么?

4

1 回答 1

-1

这是因为您声明了 2 次您的单元格:

ButtonCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ButtonCell" 
                                                             forIndexPath:indexPath];

和:

ButtonCell *cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];

尝试在 .h 文件中声明您的单元格并替换我在没有类 ButtonCell 的代码上编写的代码:

cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ButtonCell" 
                                                             forIndexPath:indexPath];

和:

cell = (ButtonCell *)[collectionView cellForItemAtIndexPath:indexPath];
于 2013-04-05T20:02:52.150 回答