Let's say you have two views view1
and view2
.
For example some data changed in view2
and you need to pass this data to view1
. I'd do this with delegation pattern. So here's the setup:
protocol View2Delegate {
func didChangeSomeData(data: String)
}
Now in view2
class View2: UIView {
var delegate: View2Delegate?
var text: String = String() {
didSet {
self.delegate.didChangeSomeData(data: text)
}
}
}
and in view1
class View1: UIView, View2Delegate {
var textToChange: String = String()
func didChangeSomeData(data: String) {
// Do whatever you want with that changed data from view2
textToChange = data
}
}
and in your viewController
class MyViewController: UIViewController {
var: view1 = View1()
var: view2 = View2()
func viewDidLoad() {
super.viewDidLoad()
view2.delegate = view1
}
Now, if you don't really want to couple view1
and view2
, you could listen via the same pattern changes of view2
in ViewController
and then pass it directly to the view1
via property accessor.
class MyViewController: UIViewController, View2Delegate {
var: view1 = View1()
var: view2 = View2()
func viewDidLoad() {
super.viewDidLoad()
view2.delegate = self
}
func didChangeSomeData(data: String) {
view1.textToChange = data
}
More on protocols in the Apple's Documentation
Update
You could also go with Key Value Observing pattern. You could setup it like this:
class MyViewController: UIViewController {
var view1 = View1()
var view2 = View2()
override func viewDidLoad() {
super.viewDidLoad()
let observation = view2.observe(\.text) { (observed, change) in
if let newValue = change.newValue {
view1.textToChange = newValue
}
}
}
}