ios - UICollectionView 添加按钮到单元格

标签 ios uicollectionview

我正在向 Collection View 的单元格添加一个按钮,如下所示

- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
    if (gr.state == UIGestureRecognizerStateBegan)
    {
        NSLog(@"deletion mode");

        if(self.isDeleteActive == NO){
            self.isDeleteActive = YES;
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[gr locationInView:self.collectionView]];
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
            self.deletedIndexpath = indexPath.row;


            self.deleteButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [self.deleteButton addTarget:self
                       action:@selector(deleteImage:)
             forControlEvents:UIControlEventTouchUpInside];
            [self.deleteButton setBackgroundImage: [UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
            self.deleteButton.frame = CGRectMake(10, 0, 10, 10);

            [cell addSubview:self.deleteButton];
        }
    }
}

问题是,当滚动 Collection View 时重用单元格时,我也看到该单元格中显示的按钮。我该如何避免这种情况发生?下面的 Collection View 代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];
    cell.image.image = [self.imageArray objectAtIndex:indexPath.row];
    return cell;
}

最佳答案

过去我做过这样的事情,在添加 View 时添加一个标签:

self.deleteButton.frame = CGRectMake(10, 0, 10, 10);

//Mark the view with a tag so we can grab it later
self.deleteButton.tag = DELETE_BUTTON_TAG;
[cell addSubview:self.deleteButton];

然后将其从任何新的回收电池中移除:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];

    //Remove the delete view if it exists
    [[cell viewWithTag:DELETE_BUTTON_TAG] removeFromSuperview];
    cell.image.image = [self.imageArray objectAtIndex:indexPath.row];
    return cell;
}

关于ios - UICollectionView 添加按钮到单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29758692/

相关文章:

ios - Swift - 占位符长文本 - 切中间

ios - 在 Objective-C 项目中导入纯 Swift 框架

ios - 如何更新之前选择的 CollectionView 单元格和现在的 Swift 4?

ios - 如何在重置设备列表时从苹果开发者帐户中删除设备

ios - 异常构建 gradle 任务 launchIosDevice

iOS 5 需要 ARC 桥接转换

ios - 配置 UICollectionView 以保持相同的单元格 View

ios - UICollectionView 和补充 View (标题)

ios - 使用动画更改 CollectionView 位置,但在第一次滚动时向后移动

ios - UICollectionViewCell 向 UICollectionView didSelect 发出信号