2011-01-05 53 views
43

我附上一个UISwipeGestureRecognizerUITableViewCellcellForRowAtIndexPath:方法,像这样:UIGestureRecognizer和UITableViewCell的问题

- (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]; 

     UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 
     gesture.direction = UISwipeGestureRecognizerDirectionRight; 
     [cell.contentView addGestureRecognizer:gesture]; 
     [gesture release]; 
    } 
    return cell; 
} 

然而,didSwipe方法总是得到成功的刷卡叫了两声。我最初以为这是因为手势开始和结束,但如果我注销gestureRecognizer本身,他们都处于“已结束”状态:

-(void)didSwipe:(UIGestureRecognizer *)gestureRecognizer { 

    NSLog(@"did swipe called %@", gestureRecognizer); 
} 

控制台:

2011-01-05 12:57:43.478 App[20752:207] did swipe called <UISwipeGestureRecognizer: 0x5982fa0; state = Ended; view = <UITableViewCellContentView 0x5982c30>; target= <(action=didSwipe:, target=<RootViewController 0x5e3e080>)>; direction = right> 
2011-01-05 12:57:43.480 App[20752:207] did swipe called <UISwipeGestureRecognizer: 0x5982fa0; state = Ended; view = <UITableViewCellContentView 0x5982c30>; target= <(action=didSwipe:, target=<RootViewController 0x5e3e080>)>; direction = right> 

我是真的真的不知道为什么。我试着明确地检查了Ended状态,但这没有任何帮助,因为它们都以“End”结尾......任何想法?

回答

109

不是直接将手势识别器添加到单元格中,而是将其添加到viewDidLoad的tableview中。

didSwipe - 方法可以判断影响IndexPath和细胞如下:

-(void)didSwipe:(UIGestureRecognizer *)gestureRecognizer { 

    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) { 
     CGPoint swipeLocation = [gestureRecognizer locationInView:self.tableView]; 
     NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation]; 
     UITableViewCell* swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath]; 
     // ... 
    } 
} 
+0

谢谢!这阻止了它发射两次! :) – mootymoots 2011-01-05 17:55:03

+0

谢谢,这有帮助,但我看到一些奇怪的 - 刷卡后,如果我想选择行,我需要按两次。第一次什么都不做,第二次调用didSelectRow ...有人看到了这个? – 2013-02-27 09:34:44

+1

@OdedBenDov我相信这是由手势识别器引起的,当我添加了轻击手势识别器并忘记删除文本字段的末尾编辑方法(表格视图单元格的子视图)时,我有奇怪的表格视图单元格选择行为,可能是这可以作为解决你的问题的线索,更多细节[这里](http://stackoverflow.com/questions/9939509/strange-behavior-did-select-row-touch-not-responding-for-uitableviewcell) – 2013-08-28 10:26:19

0

它将与应用程序代理工作

- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

// code 

} 
+2

应用程序委托?嗯? – quantumpotato 2013-10-22 00:30:25

+0

tableview委托 – 2015-10-09 07:10:25

0

我有这个同样的问题,通过勾选解决它表格视图属性中的“滚动已启用”。

我的表格视图不需要滚动,所以它不会以任何其他方式影响应用程序,除非现在我在滑动手势后没有得到第一个无响应的水龙头。