繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM