如何确定用户是否按下了UITableViewCell 2秒钟?

时间:2010-07-23 00:22:39

标签: iphone objective-c cocoa-touch uitableview uigesturerecognizer

我正在使用手势识别器:

viewDidLoad初始化:

UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
 [self.view addGestureRecognizer:longPressRecognizer];

这就是longPress的样子:

- (void)longPress:(UILongPressGestureRecognizer*)gestureRecognizer {
 if (gestureRecognizer.minimumPressDuration == 2.0) {
  NSLog(@"Pressed for 2 seconds!");
 }
}

我怎么把它绑成?

- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

didSelectRowAtIndexPath如何获得对gestureRecognizer.minimumPressDuration

的引用

基本上我想要实现的是:

**If a user clicks on a cell, check to see if the press is 2 seconds.**

3 个答案:

答案 0 :(得分:3)

尝试通过提供tableView:willDisplayCell:forRowAtIndexPath:方法将其添加到UITableViewCell而不是UITableView:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
     [cell addGestureRecognizer:longPressRecognizer];
}

答案 1 :(得分:2)

您可以尝试将gesturerecognizer添加到tableviewcell,而不是tableview。 UITableViewCells派生自UIView,因此他们可以接受手势识别器。

答案 2 :(得分:1)

将indexpath.row添加到tableviewcell的标记

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(rowButtonAction:)];
[cell setTag:indexPath.row];
[cell addGestureRecognizer:longPressRecognizer]; 
[longPressRecognizer release];

// Configure the cell...
Group *gp = [_currentItemArray objectAtIndex:indexPath.row];
cell.textLabel.text = gp.name;


return cell;

}

然后使用[[gestureRecognizer view]标签访问longPress中的标签] (在我的代码中,它的部分包含myModalViewController.previousObject = [_ currentItemArray objectAtIndex:[[sender view] tag]];

-(IBAction)rowButtonAction:(UILongPressGestureRecognizer *)sender{
if (sender.state == UIGestureRecognizerStateEnded) {
    GroupsAdd_EditViewController *myModalViewController = [[[GroupsAdd_EditViewController alloc] initWithNibName:@"GroupsAdd_EditViewController" bundle:nil] autorelease];
    myModalViewController.titleText = @"Edit Group";
    myModalViewController.context = self.context;
    myModalViewController.previousObject = [_currentItemArray objectAtIndex:[[sender view] tag]];
    [self.navigationController presentModalViewController:myModalViewController animated:YES];
}

}