swift - Get the instance of another view controller in the same tab bar
问题描述
My tab bar has 3 tabs. If I'm on the view controller of tab 1 first and then sometime later in the app I end up in tab 2, how do I get the instance of tab 1 (in code) that is currently loaded? The view controller's viewDidLoad function only gets called once so as long as I visited a tab, it's view controller is still somewhere.
Is it possible to get a reference to an instance of another view controller in a tab bar controller? I don't want to instantiate a new view controller, I want the current instance that has been loaded.
解决方案
Yes, it is possible. You can get it's instance by providing the index of the UIViewController
you want to the viewCotnrollers
property in the UITabBarController
.
class MyTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// after loading is done
let firstViewController = viewControllers?[0]
print(firstViewController?.title)
}
}
If you're trying to get the firstViewController
from the secondViewController
which is embedded inside the UINavigationController
use this:
class SecondController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// after loading is done
let firstViewController = navigationController?.tabBarController?.viewControllers?[0]
print(firstViewController?.title)
}
}
And here's the extended version in case you're not sure:
class SecondController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// after loading is done
if let navigationController = navigationController {
if let tabBarController = navigationController.tabBarController {
let firstViewController = tabBarController.viewControllers?[0]
print(firstViewController?.title)
} else {
print("I'm not embedded in a tabBar controller")
}
} else {
print("I'm not embedded in a navigation controller")
if let tabBarController = tabBarController {
let firstViewController = tabBarController.viewControllers?[0]
print(firstViewController?.title)
} else {
print("I'm not embedded in a tabBar controller")
}
}
}
}
推荐阅读
- sql-server - 查询失败后使用 SELECT-INTO 语句进行部分提交
- python - 如何在 Heroku 上保存 sqlite3 数据库?
- python - 未安装 Anaconda 中的 cryptocompare 模块以获取实时加密货币价格
- react-native - react-native 功能组件重新渲染
- bash - 在 dockerfile 中传递参数?
- asp.net-core-webapi - 在 ASP.NET CORE 上使用服务器发送的事件时如何检测断开连接?
- python - 在 python 字典中需要帮助
- python - TypeError:“函数”对象不可下标 Python/Numpy
- python - 如何从 MongoDB 的嵌套文档中更新“状态”值?
- python - 使用 Apache Airflow 的 SimpleHttpOperator 上传二进制数据的 PUT 请求