ios - 长按幻灯片放映图片

标签 ios objective-c swift collectionview

我有一个 CollectionViewCollectionView 中的单元格大小等于屏幕大小(CollectionView 具有分页启用模式)。

我想在屏幕上长按,然后 CollectionView 将滚动到下一个单元格。

例如:

我需要 1 秒才能使 CollectionView 滚动到下一个单元格, 然后我按下 2.5 秒。

开始时间:我开始长按屏幕, Collection View 现在位于第一个单元格上。

第一秒后:它将滚动到第二个单元格。

第二秒后:它将滚动到第三个单元格。

最后半秒:它仍然站在第三个单元格上(因为半秒时间不足以让 Collection View 滚动到下一个单元格)。

我已将 UILongPressGestureRecognizer 添加到单元格中,我已尝试这样做:

func handleLongPress(longGesture: UILongPressGestureRecognizer) {
        if longGesture.state == .Ended {
            let p = longGesture.locationInView(self.collectionView)
            let indexPath = self.collectionView.indexPathForItemAtPoint(p)

            if let indexPath = indexPath {
                let row = indexPath.row + 1
                let section = indexPath.section
                if row < self.photoData.count {
                self.collectionView.selectItemAtIndexPath(NSIndexPath(forRow: row, inSection: section), animated: true, scrollPosition: .Right)
                }
                print(indexPath.row)
            } else {
                print("Could not find index path")
            }
        }
    }

但我总是必须结束使 Collection View 滚动的长手势。

最佳答案

您似乎想要的是启动一个计时器,当手指按下时每 1 秒触发一次。我可能会做一个功能:

    func scrollCell() {
        if (longPressActive) {
            //scroll code

            let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
            dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
                scrollCell() // function calls itself after a second 
            })
        }
    }

你可以在你的handleLongPress代码中控制:

func handleLongPress(longGesture: UILongPressGestureRecognizer) {
     if longGesture.state == .Began {
         longPressActive = true
         scrollCell()
     } else if longGesture.state == .Ended || longGesture.state == .Canceled {
            longPressActive = false
        }
    }

因此,当长按手势第一次触发时,它会设置一个 bool (longPressActive),然后调用滚动函数。当滚动函数完成时,它会再次调用自身。如果手势最终完成,它将清除 longPressActive bool 值,因此如果计时器触发,该 bool 值将为 false 并且不会滚动。

更理想的情况是,我可能不会使用长按手势识别器,而只是自己跟踪触摸,因为我可以引用触摸并检查其状态,而不是使用 bool 值。此外,当调度进入后台时,可能存在一个有趣的错误。

关于ios - 长按幻灯片放映图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38448585/

相关文章:

ios - 这里的角落工作但阴影在 iOS 9 和 10 中不起作用

ios - 当应用程序终止或未运行时,应用程序从iOS 中的AppStore 更新时是否有回调?

ios - 设置 map 坐标范围默认显示 (0, 0)

ios - 出现错误 "command not found: faSTLane"

ios - 分发配置文件是否来自分发证书?

ios UIScrollView 有一个错误的默认 contentOffset - swift

ios - 有什么办法可以让 GCM 与 Firebase SDK v3.3 一起使用吗?

iOS——调用 contentsOfDirectoryAtPath 会在循环中泄漏内存

objective-c - 在 iOS 上舍入 NSDate 的正确方法是什么?

ios - 将 subview 添加到 UITableView 单元格的 View