Container View とMainView間でのデータ交換をNotificationCenterで実施する。
メインの ViewController
import UIKit class OrigViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(onNotification(notification:)), name: .notifyName, object: nil) } @objc func onNotification(notification:Notification) { print("OrigViewController: onNotification called") label1.text = notification.userInfo?["data"] as? String } @IBOutlet weak var label1: UILabel! @IBAction func mainButtonPressed(_ sender: Any) { NotificationCenter.default.post(name: .notifyName, object: nil, userInfo: ["data": "data from OrigViewController", "isImportant": true]) } } extension Notification.Name { static let notifyName = Notification.Name("notifyName") }
Containerの ViewController
import UIKit class ContainerViewController1: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(onNotification(notification:)), name: .notifyName, object: nil) } @objc func onNotification(notification:Notification) { print("ContainerViewController1: onNotification called") label1.text = notification.userInfo?["data"] as? String } @IBOutlet weak var label1: UILabel! @IBAction func button1Pressed(_ sender: Any) { NotificationCenter.default.post(name: .notifyName, object: nil, userInfo: ["data": "data from Container", "isImportant": true]) } }