在没有Segues的故事板之间传递变量 - Swift

时间:2015-08-17 13:25:26

标签: ios swift uiviewcontroller uistoryboardsegue

我在位于Xcode内的两个不同.storyboard文件中的两个不同的UIViewController之间传递数据。 (这是一个非常大的项目,所以我不得不把它分解成不同的故事板。)

我已经建立了一个" exercisePassed"我希望将数据传递给视图中的变量(字符串),并且我已经知道如何在位于不同故事板中的两个视图之间移动。像这样。

var storyboard = UIStoryboard(name: "IDEInterface", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("IDENavController") as! UIViewController

//**************************************
var ex = //Stuck Here
ex.exercisedPassed = "Ex1"
//**************************************

self.presentViewController(controller, animated: true, completion: nil)

如何在不使用Segue / PrepareForSegue的情况下传递数据?

4 个答案:

答案 0 :(得分:24)

我假设您要传递数据的viewController是自定义viewController。在这种情况下,请在此处使用此修订代码:

var storyboard = UIStoryboard(name: "IDEInterface", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("IDENavController") as! MyCustomViewController

controller.exercisedPassed = "Ex1"

self.presentViewController(controller, animated: true, completion: nil)

答案 1 :(得分:3)

根据我的理解,你的问题不是很清楚

//1
//create a variable in "IDENavController"
//e.g 
var someVariable = @""

//2
var controller = storyboard.instantiateViewControllerWithIdentifier("IDENavController") as!       UIViewController
controller.someVariable = [assign your variable]

//3
self.presentViewController(controller, animated: true, completion: nil)

答案 2 :(得分:2)

试试这个。这对我有用。

var storyboard = UIStoryboard(name: "IDEInterface", bundle: nil)
var controller = storyboard.instantiateViewControllerWithIdentifier("IDENavController") as! YourDestinationViewControllername
// Add your destination view controller name and Identifier

// For example consider that there is an variable xyz in your destination View Controller and you are passing "ABC" values from current viewController.

controller.xyz = "ABC"

self.presentViewController(controller, animated: true, completion: nil)

希望这会有所帮助。

答案 3 :(得分:1)

对于那些正在寻找Swift 3/4答案的人:

let storyboard = UIStoryboard(name: "IDEInterface", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "IDENavController") as! CustomViewController

controller.yourVariable = "abc"

self.present(controller, animated: true, completion: nil)