我有一个视图控制器,它有一个segue到第二个视图控制器,我传递了一些数据到第二个准备segue。 问题是:第二个视图控制器有一个容器视图,我需要与之共享该数据。我尝试使用准备segue但在这种情况下它不起作用。
更新
查看控制器代码:
class ViewController: UITableViewController, ContainerViewDelegate {
var myContainerView = ContainerView()
var id: String!
override func viewDidLoad() {
super.viewDidLoad()
id = "123"
myContainerView.delegate = self
}
func initialize() -> String {
return id
}
}
容器视图代码:
protocol ContainerViewDelegate {
func initialize() -> String
}
class ContainerView: UICollectionViewController {
var delegate: ContainerViewDelegate!
var id: String!
override func viewDidLoad() {
super.viewDidLoad()
id = delegate.initialize()
print(id)
}
}
我在第fatal error: unexpectedly found nil while unwrapping an Optional value
id = delegate.initialize()
答案 0 :(得分:1)
您正在设置委托的正确轨道。
在故事板中:
Embed Segue
创建一个类型为ContainerView
的Segue,以嵌入ViewController。Identifier
。在代码中,prepareForSegue()
:
myContainerView
属性设置代理
class ViewController: UITableViewController, ContainerViewDelegate {
var myContainerView:ContainerView? // we do initialize it in prepareForSegue()
var id: String!
override func viewDidLoad() {
super.viewDidLoad()
id = "123"
// myContainerView.delegate = self //myContainerView is nil here. We set it in prepareForSegue
}
func initialize() -> String {
return id
}
let embedSegueID = "the identifier you set to your embed segue in Storyboard"
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == embedSegueID) {
let dvc = segue.destination as! ContainerView
// Now you have a pointer to EmbeddedViewController.
// You can save the reference to it, or pass data to it.
myContainerView = dvc
myContainerView.delegate = self
}
print(segue.identifier)
}
}
如果你想将数据从ViewController传递到嵌入在destinationViewController中的AnotherViewController(我如何理解你的问题),我会:
viewWillAppear()
中的AnotherViewController。在这种情况下,我如何理解您的用例,您不需要委托,并且可以删除所有与委托相关的代码(initialize
,ContainerViewDelegate
协议,属性var delegate: ContainerViewDelegate!
以及所有代码打电话给它。
答案 1 :(得分:0)
你可以使用准备segue并发送你想要的第二个控制器...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// get a reference to the second view controller
let secondViewController = segue.destinationViewController as! SecondViewController
// set a variable in the second view controller to pass
secondViewController.data = data
}
答案 2 :(得分:0)
双向:
在第二个视图控制器中,覆盖prepare(for:sender:)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "loadContainerView" { // replace with your segue identifier
let childViewControllerController = segue.destination
// pass data
}
}
在第二个视图控制器中,使用childViewControllers
访问容器视图的控制器。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let childViewController = childViewControllers.first {
// pass your data
}
}
示例项目: https://www.dropbox.com/s/he97ldzhav2non3/ContainerViewTest.zip?dl=0