I have viewController1 that makes a modal segue to my viewController2 but the
viewController2 is embebed on a navigation controller
because I need the navigation bar there.
I've implemented a protocol to send the data back from viewController2 to viewController1 but it doesn't function. Here is my code:
protocol writeValueBackDelegate {
func writeValueBack(value: String)
}
class viewController1: UITableViewController, writeValueBackDelegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectAddress"{
if let dest = segue.destinationViewController as? MapAddressViewController{
dest.delegate = self
}
}
}
}
On the viewController2 I have this:
class viewController2: UIViewController{
var delegate: writeValueBackDelegate?
@IBAction func TaskOneClick(sender: AnyObject) {
delegate?.writeValueBack(txtAddress!.text!)
self.navigationController?.popViewControllerAnimated(true)
}
}
I dont know why but it functions only if I remove the navigation controller from my secondviewController and make the segue from viewController 1 to viewController 2 directly, but I need the navigation controller to show the navigation bar.
Do you know why it is happening? or Why I'm doing bad.
Here is my understanding of your setup.
ViewController1 -> NavigationController -> ViewController2
In this case, in the prepare for segue method, the destination viewcontroller is the Navigation Controller and Not ViewController2. Therefore, this line of code will not be true.
The downcast you have there will fail, because the destination VC is not MapAddressViewContoller,instead its a UINavigation controller.
To fix this, you can change the code as follows :
However, I prefer using NSNotification to pass data back down the view controller hierarchy. You could try that out also.
Using Notifications :
override func viewDidLoad() { NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myFunc:"), name: "SomeName", object: nil) } func myFunc(theNotifiction : NSNotification){ print("I got notified (theNotifiction.userInfo!)") }
NSNotificationCenter.defaultCenter().postNotificationName("SomeName", object: nil, userInfo: ["theKey":"theData"])
Here is the way doing this through NSNotification and CustomDelegate
Let's see the Passing Data from ViewController2 to ViewController1 Using NSNotification first.
in ViewControllerB
.h
.m
in ViewControllerA
.h
.m
First we navigate the view from ViewControllerA to ViewControllerB.
After that we send the data from ViewControllerB to ViewControllerA.
In above coding we use the NSNotification.
Let's see the Passing Data from ViewController2 to ViewController1 Using CustomDelegate.
.m
in ViewController
.h
.m
In above coding we use the CustomProtocolDelegate Method.
Likewise you can send the data to other view controller using Custom Delegate Methods or NSNotificationCenter