在新的故事板中将值传递给 UIViewController - Swift
Posted
技术标签:
【中文标题】在新的故事板中将值传递给 UIViewController - Swift【英文标题】:Passing Values to UIViewController in new Storyboard - Swift 【发布时间】:2014-08-15 10:31:55 【问题描述】:我正在尝试将值传递给新的视图控制器 - 位于新的故事板文件中。但是,当我这样做时,我从 NewViewController 得到的结果总是 nil。
以下是我在新故事板中显示视图控制器的方式:
// Show create account page with custom transition
var storyboard : UIStoryboard = UIStoryboard(name: StoryboardName, bundle: nil)
var vc : UIViewController = storyboard.instantiateViewControllerWithIdentifier(NewViewController) as UIViewController
我尝试在这里发送信息:
// Pass the delegate to the first view controller
let newViewController:NewViewController = NewViewController()
newViewController.createAccountDelegate = self
newViewController.teststring = "hello"
然后呈现视图控制器。
vc.transitioningDelegate = self
vc.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
self.presentViewController(vc, animated: true, completion: nil)
这是我的 NewViewController,我尝试在其中接收值。但是最终仍然为零。
import UIKit
class NewViewController: UIViewController
var createAccountDelegate:AccountCreationDelegate!
var teststring:NSString!
override func viewDidLoad()
super.viewDidLoad()
我是否错误地发送了值?
【问题讨论】:
【参考方案1】:您正在使用此行创建NewViewController
的新实例
let newViewController:NewViewController = NewViewController()
而是分配变量并委托给您从StoryBoard
实例化的vc
var storyboard : UIStoryboard = UIStoryboard(name: StoryboardName, bundle: nil)
// It is instance of `NewViewController` from storyboard
var vc : NewViewController = storyboard.instantiateViewControllerWithIdentifier(NewViewController) as NewViewController
// Pass delegate and variable to vc which is NewViewController
vc.createAccountDelegate = self
vc.teststring = "hello"
vc.transitioningDelegate = self
vc.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
self.presentViewController(vc, animated: true, completion: nil)
【讨论】:
为什么会发生这种情况,虽然它以前有效,但现在非常奇怪以上是关于在新的故事板中将值传递给 UIViewController - Swift的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 3.0 中将 TableViewCell 值传递给新的 ViewController?