通常在导航堆栈中删除自定义UIViewController类

时间:2015-04-04 03:20:47

标签: ios swift uinavigationcontroller generics

我想以编程方式删除UINavigationController堆栈中特定类型的某些控制器。

使用非泛型功能:

    if let navigationController = navigationController {
        var controllers = [AnyObject]()
        for item in navigationController.viewControllers {
            if !(item is CustomViewController) {
                controllers.append(item)
            }
        }

        navigationController.viewControllers = controllers
    }

但是,我试图让这个变得通用。

func removeController<T>(controller: T.Type, navigationController: UINavigationController?) {
    if let navigationController = navigationController {
        var controllerArray = [AnyObject]()
        for item in navigationController.viewControllers {
            if !(item is T.Type) {
                controllerArray.append(item)
            }
        }
        navigationController.viewControllers = controllerArray
    }

}
removeController(CustomViewController.self, navigationController)

经过多次尝试,它仍然无法正常工作。
有人可以帮帮我,谢谢你。

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

func removeController<T>(type: T.Type, navigationController: UINavigationController?) {

    if let navigationController = navigationController {
        var controllerArray = [UIViewController]()

        for item in navigationController.viewControllers as [UIViewController] {
            if !(item is T) {
                controllerArray.append(item)
            }
        }
        navigationController.viewControllers = controllerArray
    }
}

removeController(CustomViewController.self, navController)