【问题标题】:numberOfRowsInSection ErrornumberOfRowsInSection 错误
【发布时间】:2018-01-13 22:35:15
【问题描述】:

我得到一个零,我不知道为什么。每次我选择 tableViewController1 并执行 segue 时,它​​都会崩溃并将错误发送给 tableViewController2。我设置了标识符并将类设置为情节提要中的每个 tableViewController。我想要做的是将数据从tableViewController1 传递到tableViewController2

这是来自tableViewController1

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let magazines = MagazineTableViewController()
        magazines.customInit(magazinesindex: indexPath.row, title: topics[indexPath.row])
        self.performSegue(withIdentifier: "company", sender: nil)
        tableView.deselectRow(at: indexPath, animated: true)
    }

这是tableViewController2

let MagazinesData = [//an array containing arrays of magazines]
var magazinesIndex: Int!

override func viewDidLoad() {
    super.viewDidLoad()

}

func customInit(magazinesindex: Int, title: String) {
    self.magazinesIndex = magazinesindex // this is where the error is
    self.title = title
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return MagazinesData[magazinesIndex].count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MagazineTableViewCell
    cell.magazineTitle?.text = MagazinesData[magazinesIndex][indexPath.row]

    return cell
}

}

【问题讨论】:

    标签: swift uitableview variables segue


    【解决方案1】:

    对不起,你的方法完全错误。

    您必须实现 prepare(for segue 并将数据传递给 destination 的属性继续。

    • didSelectRowAt 更改为

      override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          self.performSegue(withIdentifier: "company", sender: indexPath)
          tableView.deselectRow(at: indexPath, animated: true)
      }
      
    • 像这样实现prepare(for segue

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if segue.identifier.rawValue == "company" { 
            let destinationController = segue.destination as! MagazineTableViewController
            let indexPath = sender as! IndexPath
            destinationController.customInit(magazinesindex: indexPath.row, title: topics[indexPath.row])
      
          }
      }
      

    【讨论】:

    • 谢谢!我完全忘记了为继续做准备
    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 2016-06-06
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多