数据未通过prepareForSegue从主VC传递到嵌入式VC

时间:2017-01-15 00:12:14

标签: swift3 xcode8 ios10

我正在尝试将数据从主VC(称为StartVC)传递到嵌入式VC(称为MPList - 它本身包含一个tableview)。

我发现的解决方案都指向使用prepareforsegue方法,但这似乎对我没有用。该应用程序运行时没有错误,并且表格视图没有填充我发送的数据。

在StartVC中,我已经实现了prepareforsegue方法,如下所示(在属性检查器中,embed segue肯定有一个标识符“LeftPane”。):

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "LeftPane"{
        let mpListVC = segue.destination as? MPList
        mpListVC?.mpNames = self.mpNames

    }
}

mpNames是一个在嵌入式MPList中初始化的字符串数组,如下所示(mpListTV是所讨论的tableview的IBOUTLET):

class MPList: UIViewController, UITableViewDataSource, UITableViewDelegate{


var mpNames = [String]()


override func viewDidLoad() {
    super.viewDidLoad()


    mpListTV.delegate = self
    mpListTV.dataSource = self


    print("names in MPList is: \(mpNames)")


}

通常的tableview控件方法也在MPList中实现(这也是使用mpNames的地方。):

    //MARK: - TABLEVIEW METHODS

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    return mpNames.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = mpNames[indexPath.row]

    return cell


}

我还确保右键单击并从tableview拖动到MPList视图控制器顶部的小黄色图标,并设置数据源和委托。

我可能只是累了(并且遗漏了一些非常明显的东西)现在在这里待了几个小时,但有人可以请我摆脱我的痛苦并告诉我我的错误是什么吗?

1 个答案:

答案 0 :(得分:0)

我在这里看到可能出现的问题:

1

//in prepareForSegue
let mpListVC = segue.destination as? MPList

确保IB 中的目标视图控制器确实设置为MPList。因为这个原因,mpListVC可能nil。只需调试并确保mpListVc不是零。

同时调试并确保没有可选项为nil。更好的是,使用强制解包(!)尝试在某处找到可能的nil

只需设置断点并检查mpNames是否确实已设置。

2

出于某种原因viewDidLoad之前可能会MPList prepareForSegue reloadData被调用,尽管它不应该。无论哪种方式,重置阵列后UITableView的{​​{1}}都是一个很好的做法。

 var mpNames = [String]() {
    didSet {
       mpListView?.reloadData()
    }

}
相关问题