UICollectionView的问题 - 一个选定的单元格意味着其他选择

时间:2013-04-05 18:47:25

标签: objective-c cocoa-touch ios6 uicollectionview

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

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

这是我的代码:

-(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];
}

有什么建议吗?

1 个答案:

答案 0 :(得分:-1)

这是因为你声明你的细胞的2倍:

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

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

尝试在.h文件中声明你的单元格并替换我在代码中编写的代码而不使用类ButonCell:

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

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