【发布时间】:2019-11-20 02:58:00
【问题描述】:
我正在尝试在从自定义 UINavigationController 类推送/弹出视图控制器时进行自定义转换。我正在实现UINavigationControllerDelegate 方法
navigationController(_:animationControllerFor:from:to:),但它没有被调用。
我正在情节提要中创建一个UINavigationController,并将其类设为CustomNavigationController。我还在情节提要中为其分配了一个根 ViewController(我们称其为根 VC CustomViewControllerRoot)。
这是我正在使用的代码(经过简化且未经测试):
protocol NavigationDelegate {
func pushCustomViewController()
func popViewController()
}
class CustomNavigationController: UINavigationController, NavigationDelegate {
init() {
super.init(nibName: nil, bundle: nil)
delegate = self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
self.navigationBar.isHidden = true
guard viewControllers.first is CustomViewControllerRoot else {fatalError("Error")}
rootVC = viewControllers.first as? CustomViewControllerRoot
rootVC?.navigationDelegate = self
//Setup the rest of the viewControllers that are to be used
customVC = CustomUIViewController()
customVC?.navigationDelegate = self
}
var rootVC: CustomViewControllerRoot?
var customVC: CustomViewController?
func pushCustomViewController() {
if customVC != nil {
self.pushViewController(customVC!, animated: true)
}
}
func popViewController() {
self.popViewController(animated: true)
}
}
extension CustomNavigationController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// This is never called, even though the delegate is set in the initializer to CustomNavigationController
print("TEST")
return nil
}
}
然后我让导航层次结构中的每个自定义 UIViewController 子类委托推送或弹出到上面的 CustomNavigationController。例如,这是分配给导航控制器的根 vc。由于它以 root 身份存在,因此它永远不需要推送自身或弹出,就像在呈现 CustomNavigationController 时呈现的那样。当它发现应该在它上面显示另一个 VC 时,它会委托给 CustomNavigationController:
class CustomViewControllerRoot {
var navigationDelegate: NavigationDelegate?
override func viewDidLoad(){
super.viewDidLoad()
}
@objc func someButtonPressedToPresentCustomVC(){
navigationDelegate?.pushCustomViewController()
}
}
解雇是在每个CustomViewController 内部处理的,这也将弹出委托给CustomNavigationController(我不想使用导航栏进行解雇,所以从一开始就没有“后退按钮”):
class CustomViewController: UIViewController {
var navigationDelegate: NavigationDelegate?
override func viewDidLoad(){
super.viewDidLoad()
}
@objc func dismissViewController(){
navigationDelegate?.popViewController()
}
}
据我了解,由于我在初始化程序中将delegate 变量设置为self,因此每当执行推送或弹出操作时都应该调用CustomNavigationController 扩展中的UINavigationControllerDelegate 方法?
【问题讨论】:
标签: ios swift animation uinavigationcontroller uikit