SoundShock SoundShock - 4 months ago 21
Swift Question

Pass collectionview from function to Selector (UILongPressGestureRecognizer)

So I am using a function that a user can do a long press on a

UICollectionView
(note: I have multiple collection views on my screen). This triggers an action, but when I try to pass the collection view from my
longPressFolder
function to the
handleLongPress
function, it doesn't work.

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)
}


This is the part where the code doesn't work. It says that my collection view is unresolved, but I can't seem to find a way to pass the collection view from my one function to the other.

// 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()
}
}

Answer

You can get a reference to a gesture recognizer's view if you use .view on the recognizer. So try:

let collectionview = gestureRecognizer.view as! UICollectionView
Comments