索引控制器中的索引为nil

时间:2018-04-14 10:44:08

标签: ios swift

导航阵列中的视图控制器索引始终为零。如果我打印arrayOfVCs,我可以看到控制器列表仍然我索引始终为nil

public func removeFromStack(controller :  UIViewController) -> () {
    if let currentWindow = UIApplication.shared.keyWindow {
        let arrayOfVCs = (currentWindow.rootViewController as! 
            UINavigationController).viewControllers
        if let index =  arrayOfVCs.index(of: controller)  {
            (currentWindow.rootViewController as! 
             UINavigationController).viewControllers.remove(at: index)
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:2)

请注意,在extension中,self指的是您正在调用此扩展方法的对象,因此您无需获取窗口,获取顶级VC以及类似的内容。只需使用self

此外,您将UserProfileController.self传递给方法,该方法不是视图控制器的对象,而是元类型。如果您没有可访问的VC实例并且想要使用元类型来查找要从堆栈中删除的正确项目,则可以将扩展名更改为以下内容:

extension UINavigationController {
    func removeFromStack<T: UIViewController>(vcType: T.Type) {
        if let index = viewControllers.index(where: { type(of: $0) == vcType }) {
            viewControllers.remove(at: index)
        } else {
            print("Oops! The type of VC you specified is not in the stack!")
        }
    }
}