I have been looking for an answer for this, but have only found answers for segues.
I have viewController1
with a button that segues to viewController2
. There is no code for this, I set it up through Interface builder. On viewController2
I have a button that dismisses itself with
self.dismissViewControllerAnimated(true, completion, nil)
I want to pass a string from viewController2
back to viewController1
when the view is dismissed. How do I go about doing this? Also, I am using swift.
Thanks in advance!
(Swift 2.1, Xcode 7, iOS9) If you don't want it to be tightly coupled only between 2 ViewControllers, You can also use the Notification Design Pattern (Post & Observe), which is mainly used to pass on the same object/information from one VC to multiple View Controllers.
For your scenario : In VC2.swift :
And in VC1.swift :
Common Practise is:
I used the code from the first answer in a transition between controllers WITHOUT prepareForSegue and worked for me as well. Here's the sample code.
The First View Controller:
The second View Controller:
There are two common patterns, both of which eliminate the need for viewController2 to know explicitly about viewController1 (which is great for maintainability):
Create a delegate protocol for your for viewController2 and set viewController1 as the delegate. Whenever you want to send data back to viewController1, have viewController2 send the "delegate" the data
Setup a closure as a property that allows passing the data. viewController1 would implement that closure on viewController2 when displaying viewController2. Whenever viewController2 has data to pass back, it would call the closure. I feel that this method is more "swift" like.
Here is some example code for #2: