Reputation: 4989
I'm trying to detect touch and hold gestures inside a UITableView, while keeping track of which cell was selected. I need to be able to differentiate between normal taps on a cell and touches that last longer than X seconds (probably 1s or so). The main challenge is that I'd like to do this without subclassing UITableViewCell, since doing so slowed down my scrolling significantly. I think there's probably a way to do this using an NSTimer, but I can't seem to get it working correctly. Using touchesBegan: and touchesEnded: with a timer is out, since I don't see any way to keep track of which cell was selected, unless there's some way to do that with those methods? Any help would be greatly appreciated.
Thanks in advance.
Upvotes: 2
Views: 7082
Reputation: 1658
If we are talking about cells, you may want to get the indexPath of the cell that has been pressed.
Add the gesture recognizer to the cell, right after a new instance has been allocated:
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
[cell addGestureRecognizer:longPress];
[longPress release];
Handle the long press event, and get the indexPath:
-(void) handleLongPress: (UIGestureRecognizer *)longPress {
if (longPress.state==UIGestureRecognizerStateBegan) {
CGPoint pressPoint = [longPress locationInView:table];
NSIndexPath *indexPath = [table indexPathForRowAtPoint:pressPoint];
}
}
Upvotes: 18
Reputation: 1426
Short answer: Subclass and use a UILongPressGestureRecognizer
.
Longer answer: I believe the reason you are having scrolling issues with your UITableViewCell
subclass is that the reuseIdentifier
is not matching and so cells aren't being reused. Make sure the reuseIdentifier
that you are using in your cellForRowAtIndexPath:
method matches the reuseIdentifier
that you are setting in Interface Builder for the custom UITableViewCell
nib. I had the same problem when I made my first subclass and just matching the reuseIdentifier
made everything better. :)
As far as using a UILongPressGestureRecognizer
, take a look at the documentation for UIGestureRecognizer
s and you should be able to figure it out pretty quickly.
UILongPressGestureRecognizer
Documentation
UIGestureRecognizer
Documentation
Upvotes: 3
Reputation: 15218
UILongPressGestureRecognizer is made for exactly this thing. You an create one and add it to the UITableViewCell to handle long pressses.
Upvotes: 7