Reputation: 45
Passing data to the next viewController is simple and straightforward, and can be done using prepareSegue
method. However, I can't understand how to pass data to a previous viewController in Swift(Cocoa Application)
I have a textfield in viewControllerB
and when you type something in it and press a button, I want to pass it to a label in viewControllerA
and instead of opening the viewControllerA in a new window, I just want the viewController B
to be dismissed and the passed data to be visible on the viewControllerA
.
That's all there is to it. I have been stuck on it for the past 48 hours. Any help on this will be appreciated.
Thanks!
Upvotes: 1
Views: 667
Reputation: 562
You do this using delegates. Example:
protocol NextProtocol: class {
func sendBack(value: Int)
}
class Previous: NextProtocol {
func sendBack(value: Int) {
print("I have received \(value)")
}
func prepareSegue(...) {
// get next instance
var next: Next
next.delegate = self
}
}
class Next {
weak var delegate: NextProtocol?
func someMethod() {
delegate?.sendBack(5)
}
}
Upvotes: 2