要在 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];
}
}
}
在 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)
}
}
}
类似的实现适用于UICollectionView:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = collectionView.indexPathsForSelectedItems?.first {
if let coordinator = transitionCoordinator {
coordinator.animate(alongsideTransition: { _ in
self.collectionView.deselectItem(at: indexPath, animated: true)
}, completion: { context in
if context.isCancelled {
self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
}
})
} else {
collectionView.deselectItem(at: indexPath, animated: animated)
}
}
}