UICollectionView 添加按钮到单元格

UICollectionView adding button to cell

我正在向集合视图的单元格添加一个按钮,如下所示

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

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

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

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

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