【问题标题】:Pass collectionview from function to Selector (UILongPressGestureRecognizer)将 collectionview 从函数传递到 Selector (UILongPressGestureRecognizer)
【发布时间】:2016-07-13 14:38:52
【问题描述】:

所以我正在使用一个用户可以长按UICollectionView 的功能(注意:我的屏幕上有多个集合视图)。这会触发一个操作,但是当我尝试将集合视图从我的 longPressFolder 函数传递给 handleLongPress 函数时,它不起作用。

    override func viewDidLoad() {
        super.viewDidLoad()       

        // add long press to collection View
        longPressFolder(newestFoldersCollectionView)
        longPressFolder(topFoldersCollectionView)
}

   func longPressFolder(collectionview: UICollectionView) {
        // Long press
        let lpgr : UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(FolderOverviewController.handleLongPress(_:)))
        lpgr.minimumPressDuration = 0.4
        lpgr.delegate = self
        lpgr.delaysTouchesBegan = true
        collectionview.addGestureRecognizer(lpgr)
    }

这是代码不起作用的部分。它说我的集合视图未解析,但我似乎找不到将集合视图从我的一个函数传递到另一个函数的方法。

// long press
func handleLongPress(gestureRecognizer : UILongPressGestureRecognizer){
    if (gestureRecognizer.state != UIGestureRecognizerState.Ended){
        return
    }

    let p = gestureRecognizer.locationInView(collectionview)

    if let indexPath: NSIndexPath = (collectionview.indexPathForItemAtPoint(p))!{
        //do whatever you need to do
        ...               
        }
        collectionview.reloadData()
    }        
}

【问题讨论】:

  • 您应该将视图传递给locationInView()。你的handleLongPress 函数中的collectionview 变量是从哪里得到的?
  • @shim 目前不是,问题是我似乎无法将我的 collectionView 传递给 handleLongPress 函数
  • 如果您在识别器上使用.view,您可以获得对手势识别器视图的引用。所以试试let collectionview = gestureRecognizer.view as! UICollectionView
  • 嗯,如果我尝试这个,并在我的第二个集合视图中按第二个单元格,它会选择我的第一个集合视图中的第二个单元格.. 但至少它是进度:) 我会更新代码,这样你就可以检查我是否做错了什么。
  • @shim 请回答您的解决方案,我会将其标记为正确。选择collectionview很愚蠢^^

标签: ios swift uicollectionview uitapgesturerecognizer uilongpressgesturerecogni


【解决方案1】:

如果您在识别器上使用.view,您可以获得对手势识别器视图的引用。所以试试:

let collectionview = gestureRecognizer.view as! UICollectionView

【讨论】:

    【解决方案2】:

    替换

    if let indexPath: NSIndexPath = (collectionview.indexPathForItemAtPoint(p))!{
    

    if let indexPath: NSIndexPath = ((gestureRecognizer.view as! UICollectionView).indexPathForItemAtPoint(p))!{
    

    【讨论】:

    • 没有解决我的问题。将我的代码更新为更新的版本,该版本有效,但仅适用于第一个 collectionview。即使我按下第二个。
    • 您是否在longPressFolderhandleLongPress 之外声明了collectionview 变量?
    • 并且您的 collectionViews 没有相互重叠?
    • 尝试也仅将手势识别器添加到第二个集合视图并查看,它是否有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2016-07-26
    相关资源
    最近更新 更多