滑动即可删除行而无需点击删除按钮

时间:2014-01-17 22:36:58

标签: objective-c uitableview

我知道刷卡删除功能是如何工作的,虽然我不太清楚如何制作它以便不是让删除按钮出现删除我宁愿做它以便在刷卡时删除单元格细胞向左或向右。

这是我让单元格向左注册左侧滑动手势的地方:

    UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [cell addGestureRecognizer:swipeLeft];

以下是选择器的方法:

- (void)swipeLeft:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        UITableViewCell *cell = (UITableViewCell *)gestureRecognizer.view;
        NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];

    }
}

现在从UITableview删除单元格时效果很好;但是,我需要一个动画来显示向左移动一定距离的单元格然后删除。我没有什么删除按钮。

编辑:这是带动画的删除行:

    [self.tableView deleteRowsAtIndexPaths:@[indexPath]
                          withRowAnimation:UITableViewRowAnimationLeft];

    [self.tableView reloadData];

这样删除就好了,但是我可以创建它以使其像褪色动画一样创建或者我可以修改它以便刷完指定距离之后会提交删除吗?

2 个答案:

答案 0 :(得分:1)

这是我为静态表视图进行的自定义滑动,但是应该适用于动态表视图。它将允许您滑动到设置max x postition。如果用户将其释放,它将动画回原始位置。

我已经调整了代码,因此它应该适用于动态单元格。但尚未测试。

添加此本地var

@property (nonatomic) CGFloat changeX;

只需将平移GR连接到故事板并连接到此操作。

- (IBAction)dragCell:(UIPanGestureRecognizer *) gestureRecognizer
{
    CGPoint swipeLocation = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:swipeLocation];
    UITableViewCell*swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];

    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        self.changeX = swipeLocation.x;
    }
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        CGFloat maxRight = 100; // change this to increase distance of hit point
        CGFloat newX = swipeLocation.x - self.changeX; // relative from first touch location
        if (newX <= 0) newX = 0;
        if (newX >= maxRight) {
            newX = maxRight;
            NSLog(@"Hit the point where I'll allow delete");
        }
        swipedCell.frame = CGRectMake(newX, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);
    }

    if (gestureRecognizer.state == UIGestureRecognizerStateEnded || gestureRecognizer.state == UIGestureRecognizerStateCancelled) {

        [UIView animateWithDuration:0.5 animations:^{
            swipedCell.frame = CGRectMake(0, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);
        }
        completion:^(BOOL finished) {
            //
        }];
    }
}

enter image description here

答案 1 :(得分:0)

不要调用reloadData。它杀死了动画。