我有这个目标-c方法,我试图重写为swift。
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
int index = [navigationController.viewControllers indexOfObject:viewController];
self.pageControl.currentPage = index;
}
我在使用swift写这行时遇到了困难:
int index = [navigationController.viewControllers indexOfObject:viewController];
如何访问IndexOfObject?
答案 0 :(得分:5)
在Swift 1.2(Xcode 6.x)
中let index = find(navigationController.viewControllers, viewController)!
在Swift 2.0(Xcode 7.x)
中let arrayOfVCs = navigationController.viewControllers as Array
let index = arrayOfVCs.indexOf(viewController)
答案 1 :(得分:0)
在Swift 3.0(Xcode 8.x)
中let index = navigationController.viewControllers?.index(of: viewController)
答案 2 :(得分:0)
在Swift 4中,对于TabBarController
,获取所选视图控制器的索引:
let index = tabBarController.viewControllers?.index(of: viewController)
答案 3 :(得分:0)
在 Swift 5 中,index(of element: Element)
已过时。
let index =navigationController?.viewControllers.firstIndex(of: yourController)