ios - 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)
}
}
解决方案
解决方法是改变声明数组的位置(单例对此很好),并删除不必要的插入、更新、重新加载等。
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)
}
}
推荐阅读
- python - 当我尝试将我的 Django 项目部署到 Heroku 时,它没有检测到 buildpack。有人可以帮我吗?
- javascript - 如何提取2 个标签之间的内容并将该内容放在单独的数组中
- python - Python循环中的内存错误
- php - 递归不会继续下一项
- javascript - 如何使用 ID 或 Class 在一个 amp HTML 文档的不同位置调用一个 Javascript 函数?
- python - 为什么在 Django 中运行 PostgreSQL UPDATE 时出现错误“不是在字符串格式化期间转换的所有参数”?
- python - 创建 float 的子类,以防所有算术运算都返回同一类的对象(不是 float)
- javascript - 在 React 中将子表单的数据传递给父(应用程序)
- javascript - 我必须在哪里使用等待?
- swift - SwiftUI 中应用图标上的通知图标管理