我有两个viewControllers
,都是UINavigationController
的一部分。
从View1
我可以点按UITableViewCell
并转到View2
,从View2
我可以刷回View1
。
我想知道如何才能取得这一过渡的进展,而且我未能成功完成以下任务:
override func viewDidAppear(_ animated: Bool) {
navigationController?.interactivePopGestureRecognizer?.addTarget(self, action: #selector(going))
}
@objc func going(){
print(self.transitionCoordinator?.percentComplete)
}
在转换期间调用了going
函数,但该print语句只打印nil
。我尝试使用其他视图控制器(View1和父导航控制器)无济于事。
提前致谢
答案 0 :(得分:3)
这似乎有用:
private var currentTransitionCoordinator: UIViewControllerTransitionCoordinator?
@objc private func onGesture(sender: UIGestureRecognizer) {
switch sender.state {
case .began, .changed:
if let ct = navigationController?.transitionCoordinator {
currentTransitionCoordinator = ct
}
case .cancelled, .ended:
currentTransitionCoordinator = nil
case .possible, .failed:
break
}
if let currentTransitionCoordinator = currentTransitionCoordinator {
print(currentTransitionCoordinator.percentComplete)
}
}
放手后,无法取得进展。我尝试将协调器保留更长时间并在计时器上打印值,但我甚至崩溃了。
无论如何,我认为这就是你所需要的。
TEST SCENARIO:
创建一个新项目并导航到主故事板。添加导航控制器并将其根视图控制器设置为storyboard中的ViewController
(删除自动生成的根目录)。
然后转到ViewController.swift并用以下内容覆盖它:
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let controller = navigationController, controller.viewControllers.count <= 1 { // Present it first time only
view.backgroundColor = UIColor.green
let newController = ViewController()
newController.view.backgroundColor = UIColor.red
navigationController?.interactivePopGestureRecognizer?.addTarget(newController, action: #selector(onGesture))
navigationController?.pushViewController(newController, animated: true)
}
}
private var currentTransitionCoordinator: UIViewControllerTransitionCoordinator?
@objc private func onGesture(sender: UIGestureRecognizer) {
switch sender.state {
case .began, .changed:
if let ct = navigationController?.transitionCoordinator {
currentTransitionCoordinator = ct
}
case .cancelled, .ended:
currentTransitionCoordinator = nil
case .possible, .failed:
break
}
if let currentTransitionCoordinator = currentTransitionCoordinator {
print(currentTransitionCoordinator.percentComplete)
}
}
}
当您拖动手指时,您应该可以看到打印出的百分比,从而解除当前推送的视图控制器。