SoundShock SoundShock - 1 year ago 87
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

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

override func viewDidLoad() {

// add long press to collection View

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

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

let p = gestureRecognizer.locationInView(collectionview)

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download