OGeek|极客世界-中国程序员成长平台

标题: ios - CollectionView 单元格滑动以执行操作 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:43
标题: ios - CollectionView 单元格滑动以执行操作

嗨,我正在使用 UICollectionview 水平布局开发社交网络应用程序,当我的应用程序启动 Collection View 时,最多会加载 5 个单元格,然后如果我滑动第 5 个单元格,那么那时只会分配第 6 个单元格内存。以同样的方式将第 6 个单元格滑动到第 7 个单元格。那么,我该如何实现这个过程

提前感谢您的任何建议



Best Answer-推荐答案


您需要向您的 collectionView 添加滑动手势识别器:

UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self actionselector(handleSwipeGesture];
swipeGesture.direction = UISwipeGestureRecognizerDirectionUp;
[collectionView addGestureRecognizer:swipeGesture];

然后,在 handleSwipeGesture: 中处理滑动以分配单元格。

-(void) handleSwipeGestureUISwipeGestureRecognizer *) sender
{
...
}

你可以随意调整滑动方向,这个是向上配置的。

这就是它的全部内容。主要是您不希望方向与滚动方向滑动冲突,因为我认为没有一种干净的方法来处理它。当您水平滚动时,即为滑动,因此您需要使用向上/向下滑动方向。

改为附加到单元格(在单个单元格上捕获手势)我经常使用以下方法为简单的 Collection View 执行此操作:

- (UICollectionViewCell *)collectionViewUICollectionView *)collView cellForItemAtIndexPathNSIndexPath *)indexPath
{
    ...
    UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self actionselector(handleLongPress];
    [cell addGestureRecognizer:longPressGestureRecognizer];
    ...
}

(这是一个长按,但它的工作方式相同)。在将其放入单元格的情况下,您需要在单元格上放置一个标签,然后在处理程序中引用该标签以找出它来自哪个单元格:

这是上面的一个:

- (void) handleLongPress: (UILongPressGestureRecognizer *) sender 
{
    if (sender.state != UIGestureRecognizerStateBegan)
        return;

    CGPoint p = [sender locationInView: collectionView];
    NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:p];
    if (indexPath != nil)
    {
        UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
        if (cell)
    {
    int indexOfItem = cell.tag;
        NSLog(@"Selected item = %d", indexOfItem);
    }
}

至少沿着这条线...

关于ios - CollectionView 单元格滑动以执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509121/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4