-(void)setTab:(Class)class{
int i = 0;
for (UINavigationController *controller in self.tabBarContontroller.viewControllers){
if ([controller isKindOfClass:class]){
break;
}
i++;
}
self.tabBarContontroller.selectedIndex = i;
}
func setTab<T>(_ myClass: T.Type) {
var i: Int = 0
if let controllers = self.tabBarController?.viewControllers {
for controller in controllers {
if let nav = controller as? UINavigationController, nav.topViewController is T {
break
}
i = i+1
}
}
self.tabBarController?.selectedIndex = i
}
就像 Stuart Clark 的解决方案,但是是 Swift 3,并且使用恢复标识符来找到正确的选项卡:
private func setTabById(id: String) {
var i: Int = 0
if let controllers = self.tabBarController?.viewControllers {
for controller in controllers {
if let nav = controller as? UINavigationController, nav.topViewController?.restorationIdentifier == id {
break
}
i = i+1
}
}
self.tabBarController?.selectedIndex = i
}
像这样使用它(“人类”和“机器人”也必须在故事板中为特定的视图控制器和它的恢复 ID 设置,或者使用故事板 ID 并检查“使用故事板 ID”作为恢复 ID) :
struct Tabs {
static let Humans = "Humans"
static let Robots = "Robots"
}
setTabById(id: Tabs.Robots)