我在表格视图中附加了一个滑动识别器
- (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];
//swipe recognition
UISwipeGestureRecognizer *g = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(cellWasSwiped:)];
[cell addGestureRecognizer:g];
[g release];
}
// Configure the cell...
[[cell textLabel] setText:[NSString stringWithFormat:@" number %d", indexPath.row]];
return cell;
}
,滑动功能
- (void)cellWasSwiped:(UIGestureRecognizer *)g {
NSLog(@"sunt in cellWasSwiped");
swipeViewController *svc = [[swipeViewController alloc]init];
[self.navigationController pushViewController:svc animated:YES];
[svc release];
}
通过引入断点,我看到我的滑动功能被调用了2次,并且我的导航控制器上有两个相同的视图控制器。当我滑动一个单元格时,为什么我的滑动功能被调用了两次?
答案 0 :(得分:4)
在更改cellWasSwiped
州时,您的UIGestureRecognizer
可以被多次调用。您需要检查属性state
,当用户完成其操作时,它将为UIGestureRecognizerStateEnded
。检查状态UIGestureRecognizerStateFailed
和UIGestureRecognizerStateCancelled
。
答案 1 :(得分:3)
我在表格单元格中滑动时遇到了同样的问题。我的识别器方法使用状态UIGestureRecognizerStateEnded调用两次。
我按照以下方式解决了这个问题:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//... create cell
//... create swipe recognizer (in my case attached to cell's contentView)
}
for (UIGestureRecognizer* g in cell.contentView.gestureRecognizers)
g.enabled = YES;
}
然后
-(void) cellWasSwiped: (UIGestureRecognizer*) recognizer {
if (recognizer.state != UIGestureRecognizerStateEnded)
return;
if (recognizer.enabled == NO)
return;
recognizer.enabled = NO;
//... handle the swipe
//... update whatever model classes used for keeping track of the cells
// Let the table refresh
[theTable reloadData];
}
答案 2 :(得分:1)
您可以将其添加到viewDidLoad
的表格视图中,而不是直接将手势识别器添加到单元格中。
在cellWasSwiped
- 方法中,您可以按如下方式确定受影响的IndexPath和单元格:
-(void)cellWasSwiped:(UIGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
CGPoint swipeLocation = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
UITableViewCell* swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
// ...
}
}