使用后退手势以交互方式取消选择所选的UITableViewCell

Jor*_*n H 10 objective-c uitableview uigesturerecognizer ios

在iOS 7应用程序(例如"设置")中,当您点击"常规"等行时,从屏幕左侧滑动,可以看到所选行背景颜色的取消选择从灰色变为白色,并且完全消失交互式 - 如果你向上滑动一半然后向后滑动则返回灰色.

在我的应用程序中,我没有更改任何默认行为,当我从左侧滑动返回时,所选的单元格背景颜色保持完全灰色,直到滑动手势完成,然后它快速淡化为白色.

如何通过滑动实现行的交互取消选择以返回手势?

Dim*_*ima 13

似乎clearsSelectionOnViewWillAppear实际上可能会被调用viewDidAppear:而不是viewWillAppear:变换只有在转换完全结束时才会发生变化,并且如果取消交互式转换,它根本不会发生(如果它在viewWillAppear:,它会发生).这看起来像一个UIKit错误,因为文档清楚地说它应该被调用viewWillAppear:

将以下代码行放入viewWillAppear:,您将获得您正在寻找的确切行为,我只是尝试了.这可能是属性触发的确切行为,只是在错误的方法中.

[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
Run Code Online (Sandbox Code Playgroud)


Jor*_*n H 6

在11之前的iOS版本中,添加功能[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];非常出色,可以启用交互式单元取消选择。感谢@Dima!

从iOS 11开始,由于交互式过渡的更改,此功能不再起作用。要在iOS 11+上启用交互式取消选择,可以使用,UITableViewController因为它为您实现了取消选择,否则可以通过在过渡协调器旁边为取消选择设置动画来实现它,如下所示:

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
    if (selectedIndexPath) {
        if (self.transitionCoordinator) { 
            [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) { 
                [self.tableView deselectRowAtIndexPath:selectedIndexPath animated:YES]; 
            } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { 
                 if (context.cancelled) { 
                     [self.tableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; 
                 } 
            }]; 
        } else { 
             [self.tableView deselectRowAtIndexPath:selectedIndexPath animated:animated]; 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在Swift中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let selectedIndexPath = tableView.indexPathForSelectedRow {
        if let coordinator = transitionCoordinator {
            coordinator.animate(alongsideTransition: { context in
                self.tableView.deselectRow(at: selectedIndexPath, animated: true)
            }) { context in
                if context.isCancelled {
                    self.tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none)
                }
            }
        } else {
            self.tableView.deselectRow(at: selectedIndexPath, animated: animated)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)