Passing NSString via prepareForSegue - Swift

I am trying to pass a string to my Modal controller as shown below using the prepareForSegue method. See below:

Here is my initial view controller, where I will present the modal view:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier == "newProject" { var newProjectVC:ModalViewController = ModalViewController() newProjectVC = segue.destinationViewController as ModalViewController newProjectVC.testString = "hello" } } 

Here is my modal view controller:

 import UIKit class ModalViewController: UIViewController { var testString:NSString! override func viewDidLoad() { println(self.testString) } } 

Here's what it looks like in a storyboard:! [enter image description here] [1]

The problem is that it throws an exception on this line:

  newProjectVC = segue.destinationViewController as ModalViewController 

I have a feeling that it might be something to do with the navigation controller, but I'm not sure any ideas?

+6
source share
1 answer

You are correct that destinationViewController is a navigation controller and not a ModalViewController, try the following:

 let navigationController = segue.destinationViewController as UINavigationController let newProjectVC = navigationController.topViewController as ModalViewController newProjectVC.testString = "hello" 
+13
source

Source: https://habr.com/ru/post/973981/


All Articles