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

时间:2014-05-27 16:19:05

标签: ios objective-c uitableview uigesturerecognizer

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

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

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

2 个答案:

答案 0 :(得分:13)

好像clearsSelectionOnViewWillAppear可能实际上被viewDidAppear:调用而不是viewWillAppear:只有在转换完全结束后才会发生更改,并且如果取消交互式转换,则会发生更改根本没有发生(如果它在viewWillAppear:,它会)。这似乎是一个UIKit错误,因为文档清楚地说明它应该在viewWillAppear:中调用

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

[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];

答案 1 :(得分:3)

在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]; 
        }
    }
}

在斯威夫特:

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)
        }
    }
}
相关问题