有时候我们需要直接获取到当前显示的UINavigationController,以便于后续操作,
获取方法如下。此方法可以获取present出来的UINavigationController。
var navigationController : UINavigationController? {
get {
var parent: UIViewController?
if let window = UIApplication.shared.delegate?.window,let rootVC = window?.rootViewController {
parent = rootVC
while (parent?.presentedViewController != nil) {
parent = parent?.presentedViewController!
}
if let tabbar = parent as? UITabBarController ,let nav = tabbar.selectedViewController as? UINavigationController {
return nav
}else if let nav = parent as? UINavigationController {
return nav
}
}
return nil
}
}
有时候我们需要在UIView中实现跳转,每次都用block回调很麻烦,那么可以实现一个UIView的Extension
extension UIView {
open func show(_ vc: UIViewController, sender: Any?) {
viewController?.show(vc, sender: sender)
}
open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
viewController?.present(viewControllerToPresent, animated: flag, completion: completion)
}
public var viewController: UIViewController? {
var next: UIResponder?
next = self.next
repeat {
if let vc = next as? UIViewController {
return vc
} else {
next = next?.next
}
} while next != nil
return nil
}
}
有时候我们通过present跳转了多个页面,想要dismiss到根视图:
private func dismissToRootViewController() {
var vc: UIViewController = self
while vc.presentingViewController != nil {
vc = vc.presentingViewController!
}
vc.dismiss(animated: true, completion: nil)
}