2011-01-05 35 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

我有這個同樣的問題,通過勾選解決它表格視圖屬性中的「滾動已啓用」。

我的表格視圖不需要滾動,所以它不會以任何其他方式影響應用程序,除非現在我在滑動手勢後沒有得到第一個無響應的水龍頭。