UIGestureRecognizer 和 UITableViewCell 问题 [英] UIGestureRecognizer and UITableViewCell issue
问题描述
我在 cellForRowAtIndexPath:
方法中将 UISwipeGestureRecognizer
附加到 UITableViewCell
,如下所示:
I am attaching a UISwipeGestureRecognizer
to a UITableViewCell
in the cellForRowAtIndexPath:
method like so:
- (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 本身,它们都处于结束"状态:
However, the didSwipe
method is always getting called twice on successful swipe. I initially thought this was because the gesture starts and ends, but if I log out the gestureRecognizer itself, they are both in the "Ended" state:
-(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 状态,但这无济于事,因为无论如何它们都以Ended"形式出现......有任何想法吗?
I really really don't know why. I tried obviously checking for the Ended state, but that is no help as they both come in as "Ended" anyway... Any ideas?
推荐答案
可以在viewDidLoad
中将手势识别器添加到tableview中,而不是直接将手势识别器添加到单元格中.
Instead of adding the gesture recognizer to the cell directly, you can add it to the tableview in viewDidLoad
.
在 didSwipe
-Method 中,您可以确定受影响的 IndexPath 和单元格,如下所示:
In the didSwipe
-Method you can determine the affected IndexPath and cell as follows:
-(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];
// ...
}
}
这篇关于UIGestureRecognizer 和 UITableViewCell 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!