拖动UICollectionViewCells以选择iOS

时间:2016-04-12 17:00:34

标签: ios objective-c uicollectionview

我正在尝试复制iOS9功能,您可以拖动以选择多张照片,或者UICollectionViewCells:https://i.ytimg.com/vi/LZRTu3B5zlY/maxresdefault.jpg

我看到one answer here,但作为初学iOS和Objective-c开发人员,我无法弄清楚该怎么做。

我也尝试过this question,但我无法选择任何内容。

我尝试了一些代码,但根本无法得到任何回复。

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    self.startPoint = [touch locationInView:self.collectionView];
    self.selectionBox = CGRectMake(self.startPoint.x, self.startPoint.y, 0, 0);
    [self.collectionView setNeedsDisplay];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self.collectionView];
    _selectionBox.size.width = currentPoint.x - (self.selectionBox.origin.x);
    _selectionBox.size.height = currentPoint.y - (self.selectionBox.origin.y);
    self.selectionBox = CGRectMake(self.startPoint.x, self.startPoint.y, 0, 0);
    // select all the cells in this selectionBox area
    [self.collectionView setNeedsDisplay];

}

有关如何编码的任何指示?非常感谢。

2 个答案:

答案 0 :(得分:3)

answer几乎总结了

  

您可以使用UIPanGestureRecognizer。并根据的位置   平移事件,跟踪通过的细胞。当手势   结束,你会有一系列选定的单元格。

     

确保cancelsTouchesInView设置为NO。你需要设置   代表与   gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:   和gestureRecognizerShouldBegin实现以确保   CollectionView仍然可以滚动

我能够制作出一些可以帮助你入门的代码:

- (void) didPanToSelectCells:(UIPanGestureRecognizer*) panGesture{
    if (!selectionMode){
        [self.collectionView setScrollEnabled:YES];
        return;
    }else{
        if (panGesture.state == UIGestureRecognizerStateBegan){
            [self.collectionView setUserInteractionEnabled:NO];
            [self.collectionView setScrollEnabled:NO];

        }else if (panGesture.state == UIGestureRecognizerStateChanged){
            CGPoint location = [panGesture locationInView:self.collectionView];

            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:location];

            if (![selectedIndexes containsObject:@(indexPath.row)]){
                // highlight the cell using a method
                [self highlightCell:[self.collectionView cellForItemAtIndexPath:indexPath] selected:YES];
            }
        }else if (panGesture.state == UIGestureRecognizerStateEnded){
            [self.collectionView setScrollEnabled:YES];
            [self.collectionView setUserInteractionEnabled:YES];
        }
    }
}

您需要一个包含项目的集合视图。

然后你需要创建UIPanGestureRecognizer并将其添加到collectionview并将手势动作设置为didPanToSelectCells:

如果我们处于选择模式(在示例中名为selectionMode的布尔值),则仅监听平移手势

从那里你需要根据用户的触摸位置将所选对象添加到一个数组(在示例中名为selectedIndexes),然后突出显示该单元格。

答案 1 :(得分:0)

如果您的目标是 iOS 13 及更高版本,您现在可以在集合视图和表格视图中使用 iOS 的内置多选手势:请参阅Selecting Multiple Items with a Two-Finger Pan Gesture。确保将 collectionView.allowsMultipleSelectionDuringEditing 设置为 true