UICollectionView向单元格添加按钮

时间:2015-04-20 21:25:13

标签: ios uicollectionview

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

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

1 个答案:

答案 0 :(得分:2)

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

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