简体   繁体   English

从 uinavigationcontroller 中查找 uiviewcontroller

[英]Find a uiviewcontroller from uinavigationcontroller

I am trying to figure out a generic way to find a uiviewcontroller which is auto type casted.我试图找出一种通用方法来找到自动类型转换的 uiviewcontroller。 Currently, I do have this.目前,我确实有这个。

extension UINavigationController {

    func contoller(ofType type:AnyClass) -> UIViewController? {
        for controller in self.viewControllers {
            if controller.isKind(of: type) {
                return controller
            }
        }
        return nil
    }
}

Calling will be like:调用将像:

if let controller = self.navigationController?.contoller(ofType: MyController.self) as? MyController{}

That's how I am able to get controller object and I need to type cast it also.这就是我能够获得 controller object 的方式,我还需要输入 cast 。 I am trying to figure out a way to do this like as:我试图找出一种方法来做到这一点,如:

if let controller:MyController = self.navigationController?.contoller(ofType: MyController.self){}

So that I will not need to do any type casting.这样我就不需要进行任何类型转换。

For this, I may need to do some changes in UINavigationController extension function.为此,我可能需要对 UINavigationController 扩展 function 进行一些更改。 Need some suggestion for this.需要一些建议。

Use Generics:使用 Generics:

extension UINavigationController {
    func controller<T: UIViewController>(ofType _: T.Type) -> UIViewController? {
        for controller in viewControllers where controller is T {
            return controller
        }
        return nil
    }
}

EDIT 1: I would return also the VC as type we requested.编辑 1:我也会将 VC 作为我们要求的类型返回。

And recommend to use first in the name, cause there might be more than one.并建议在名称中使用 first,因为可能不止一个。 And you might want to introduce lastController(as:) in the future并且您可能希望在将来引入 lastController(as:)

extension UINavigationController {
    func firstController<T: UIViewController>(as _: T.Type) -> T? {
        for case let controller as T in viewControllers {
            return controller
        }
        return nil
    }
}

Then usage could be:那么用法可能是:

let nav = UINavigationController()
nav.viewControllers = [UIViewController(), UITabBarController()]
let tabVC = nav.firstController(as: UITabBarController.self)

EDIT 2: You can shorten the extension body:编辑 2:您可以缩短扩展体:

extension UINavigationController {
    func firstController<T: UIViewController>(as _: T.Type) -> T? {
        viewControllers.first(where: { $0 is T }) as? T
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM