tags:

views:

922

answers:

2

Hi,

How do we detect a Tap & Hold on a UITableView cell (with and without disclosure buttons on the right).. ?

A: 

You should probably handle the UIControlTouchDown event and depending on what you mean by "hold", fire a NSTimer that will count an interval since you initiated the touch and invalidate upon firing or releasing the touch (UIControlTouchUpInside and UIControlTouchUpOutside events). When the timer fires, you have your "tap & hold" detected.

luvieere
I'm can of not enough expert to come from this answer to actual code... But I mean by Hold the same behaviour in Mobile Safari when tapping and holding an URL to have an action sheet pop up to show options regarding this URL
JFMartin
+3  A: 

Here's the code lifted straight from my app. You should add these methods (and a boolean _cancelTouches member) to a class you derive from UITableViewCell.

-(void) tapNHoldFired {
    self->_cancelTouches = YES;
   // DO WHATEVER YOU LIKE HERE!!!
}
-(void) cancelTapNHold {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tapNHoldFired) object:nil];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self->_cancelTouches = NO;
    [super touchesBegan:touches withEvent:event];
    [self performSelector:@selector(tapNHoldFired) withObject:nil afterDelay:.7];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self cancelTapNHold];
    if (self->_cancelTouches)
        return;
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [self cancelTapNHold];
    [super touchesMoved:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self cancelTapNHold];
    [super touchesCancelled:touches withEvent:event];
}
DenNukem
You should never use code like this self->_cancelTouches = YES;Instead of just use self.cancelTouches = YES;and declare property private
Igor
Bullshit. It works just fine. To quote your own words from 4/24/09: "You should know, that property is just syntax sugar."
DenNukem
What is this syntax "->_" ? never seen it before :)
hakewake