繁体   English   中英

拖过 UICollectionViewCells 以选择 iOS

[英]Drag over UICollectionViewCells to select iOS

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

我在这里看到了一个答案,但作为 iOS 初学者和 Objective-c 开发人员,我不知道该怎么做。

我也尝试从这个问题开始工作,但我无法选择任何东西。

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

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

}

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

这个答案几乎总结了它

您可以使用 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),然后突出显示该单元格。

如果您的目标是 iOS 13 及更高版本,您现在可以在集合视图和表格视图中使用 iOS 的内置多选手势:请参阅使用双指平移手势选择多个项目 确保将collectionView.allowsMultipleSelectionDuringEditing设置为true

暂无
暂无

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

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