首页 文章

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

提问于
浏览
10

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

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

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

2 回答

  • 3

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

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

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

    在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)
            }
        }
    }
    

相关问题