导航数组中视图控制器的索引始终为零。如果我打印arrayofvc,我仍然可以看到控制器列表,我得到的索引总是零
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)
}
}
}
最佳答案
注意,在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!")
}
}
}