Like Stuart Clark's solution but for Swift 3 and using restoration identifier to find correct tab:
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
}
Use it like this ("Humans" and "Robots" must also be set in storyboard for specific viewController and it's Restoration ID, or use Storyboard ID and check "use storyboard ID" as restoration ID):
struct Tabs {
static let Humans = "Humans"
static let Robots = "Robots"
}
setTabById(id: Tabs.Robots)
Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:
if controller.restorationIdentifier == id {