首页 > 解决方案 > UITableView 从其他 Viewcontroller 添加行

问题描述

我有两个视图控制器,一个带有 3 个表视图,另一个控制器我有一个 uitextfield,在文本字段中输入的文本我想将它添加到另一个视图控制器中名为 ScheduleTableView 的表视图之一。这是我的代码,但我在展开可选值时意外发现 nil 错误vc.ScheduleTableView.beginUpdates()

@IBAction func addButtonTapped(_ sender: YTRoundedButton) {
   self.performSegue(withIdentifier: "secondvc", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier  == "secondvc" {
        print(TitleTextField.text!)

        let vc = segue.destination as! GrowthMainViewController

        vc.ScheduleArray.append(TitleTextField.text!)
        let indexPath = IndexPath(row: vc.ScheduleArray.count - 1, section: 0)
        vc.ScheduleTableView.beginUpdates()
        vc.ScheduleTableView.insertRows(at: [indexPath], with: .automatic)
        vc.ScheduleTableView.reloadData()
        vc.ScheduleTableView.endUpdates()



        TitleTextField.text = ""
        view.endEditing(true)

  }     
}

标签: iosswiftxcodeuitableviewuitextfield

解决方案


解决方法是改变声明数组的位置(单例对此很好),并删除不必要的插入、更新、重新加载等。

numRowsInSection 方法然后调用 scheduleArray.count 以显示所有相应的数据。

前:

@IBAction func addButtonTapped(_ sender: YTRoundedButton) {
   self.performSegue(withIdentifier: "secondvc", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier  == "secondvc" {
        print(TitleTextField.text!)

        let vc = segue.destination as! GrowthMainViewController

        vc.ScheduleArray.append(TitleTextField.text!)
        let indexPath = IndexPath(row: vc.ScheduleArray.count - 1, section: 0)
        vc.ScheduleTableView.beginUpdates()
        vc.ScheduleTableView.insertRows(at: [indexPath], with: .automatic)
        vc.ScheduleTableView.reloadData()
        vc.ScheduleTableView.endUpdates()



        TitleTextField.text = ""
        view.endEditing(true)

  }     
}

后 :

@IBAction func addButtonTapped(_ sender: YTRoundedButton) {
   self.performSegue(withIdentifier: "secondvc", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier  == "secondvc" {

        guard let text = TitleTextField.text else { return }
        scheduleArray.append(text)
        TitleTextField.text = ""
        view.endEditing(true)

  }     
}

推荐阅读