I was wondering how to add a long press gesture recognizer to a (subclass of) UICollectionView. I read in the documentation that it is added by default, but I can't figure out how.
What I want to do is: Long press on a cell ( I have a calendar thingy from github ), get which cell is tapped and then do stuff with it. I need to know what cell is longpressed. Sorry for this broad question, but i couldn't find anything better on either google or SO
Answers here to add a custom longpress gesture recognizer are correct however according to the documentation here: the parent class of
UICollectionView
class installs adefault long-press gesture recognizer
to handle scrolling interactions so you must link your custom tap gesture recognizer to the default recognizer associated with your collection view.The following code will avoid your custom gesture recognizer to interfere with the default one:
Perhaps, using UILongPressGestureRecognizer is the most widespread solution. But I encounter with it two annoying troubles:
Let me suggest one a little bit bruteforce, but working as it's required suggestion:
Declaring a callback description for long click on our cell:
typealias OnLongClickListener = (view: OurCellView) -> Void
Extending UICollectionViewCell with variables (we can name it OurCellView, for example):
Adding two methods in our cell class:
And overriding touch events here:
Then somewhere in controller of our collection view declaring callback listener:
And finally in cellForItemAtIndexPath setting callback for our cells:
Now we can intercept long click actions on our cells.
and add the method like this.
To have an external gesture recognizer and do not conflict with internal gesture recognizers on the UICollectionView you need to:
Add your gesture recognizer, set up it and capture a reference for it somewhere (the best option is on your subclass if you subclassed UICollectionView)
Override default initialization methods
initWithFrame:collectionViewLayout:
andinitWithCoder:
and add set up method for you long press gesture recognizerWrite your setup method so it instantiates long press gesture recognizer, set it's delegate, setup dependencies with UICollectionView gesture recognizer (so it be the main gesture and all other gestures will wait till that gesture fails before being recognized) and add gesture to the view
Also don't forget to implement UIGestureRecognizerDelegate methods that fails that gesture and allow simultaneous recognition (you may or may don't need to implement it, it depends on other gesture recognizers you have or dependencies with internal gesture recognizers)
credentials for that goes to internal implementation of LXReorderableCollectionViewFlowLayout
Use the delegate of UICollectionView receive long press event
You must impl 3 method below.
The same code @abbood's code for Swift:
In viewDidLoad:
And the function:
Do not forget the delegate
UIGestureRecognizerDelegate