Я предполагаю, что ваши дочерние контроллеры создаются одновременно с созданием контроллера вкладок. В тех случаях, когда необходимо уведомить другие существующие контроллеры, вы должны использовать NotificationCenter .
Механизм рассылки уведомлений, позволяющий передавать информацию зарегистрированным наблюдателям.
extension Notification.Name {
static let didReceiveCountData = Notification.Name("didReceiveCountData")
}
class tab1Controller: UIViewController {
@IBOutlet weak var countLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Listen notifications for name .didReceiveCountData.
// onDidReceiveCountData(_:) will be called when notification received.
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveCountData(_:)), name: .didReceiveCountData, object: nil)
}
// This will be called when the count changes.
@objc func onDidReceiveCountData(_ notification:Notification) {
if let newCount = notification.object as? String {
countLabel.text = newCount
}
}
// Call this when you need to change count and notify other tabs.
private func changeCount(_ newCount: String) {
NotificationCenter.default.post(name: .didReceiveCountData, object: newCount)
}
}
class tab2Controller: UIViewController {
@IBOutlet weak var countLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Listen notifications for name .didReceiveCountData.
// onDidReceiveCountData(_:) will be called when notification received.
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveCountData(_:)), name: .didReceiveCountData, object: nil)
}
// This will be called when the count changes.
@objc func onDidReceiveCountData(_ notification:Notification) {
if let newCount = notification.object as? String {
countLabel.text = newCount
}
}
// Call this when you need to change count and notify other tabs.
private func changeCount(_ newCount: String) {
NotificationCenter.default.post(name: .didReceiveCountData, object: newCount)
}
}