【发布时间】:2020-11-27 04:27:32
【问题描述】:
我正在尝试快速创建一个非常简单的待办事项列表应用程序,当我在 UITableView 上调用 reloadData 方法时,我收到此错误:“在隐式展开可选值时意外发现 nil”。当用户在与 tableView 不同的视图控制器上的文本字段中键入内容后单击添加按钮时,我正在调用此方法。他们键入的内容应该被添加到表格视图中,但它没有,我只是得到一个错误。
我在网上查找了遇到类似问题的人,但我不知道如何将它们实现到我的代码中,或者我不理解它们,因为我对 swift 非常陌生。我还尝试将文本字段与表格视图放在同一个视图控制器上并解决了问题,所以我猜它与此有关。
我的所有代码都在 ViewController.swift 中。这里是:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var editButton: UIBarButtonItem!
@IBOutlet weak var textField: UITextField!
var tableViewData = ["Apple", "Banana", "Orange", "Peach", "Pear"]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: Tableview methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = tableViewData[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// print(tableViewData[indexPath.row])
}
// Allows reordering of cells
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
// Handles reordering of cells
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = tableViewData[sourceIndexPath.row]
tableViewData.remove(at: sourceIndexPath.row)
tableViewData.insert(item, at: destinationIndexPath.row)
}
// Allow the user to delete cells
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
tableViewData.remove(at: indexPath.row)
tableView.reloadData()
}
}
// MARK: IBActions
@IBAction func edit(_ sender: Any) {
tableView.isEditing = tableView.isEditing
switch tableView.isEditing {
case true:
editButton.title = "Done"
case false:
editButton.title = "Edit"
}
}
@IBAction func add(_ sender: Any) {
let item: String = textField.text!
tableViewData.append(item)
textField.text = ""
tableView.reloadData() // <------ **This line gives me the error**
}
}
另外,我尝试了可选链接,这给我写了一个错误,tableView?.reloadData()。它使错误消失,但没有任何项目被添加到表格视图中。
不确定是否有必要,但这是故事板的图像,因此您可以看到所有屏幕
抱歉,如果这是一个非常明显的问题。就像我说的,我对 swift 和 iOS 应用程序很陌生。
提前致谢!
【问题讨论】:
-
确保 tableView IBOutlet 已连接到情节提要。
-
请务必检查情节提要中的表格视图是否正确连接到您的视图控制器类上的 tableView IBOutlet。
-
实现方法 numberOfSection ... 并返回 1
-
@jawadAli 没有修复它。
-
@Aaron 它似乎连接正确。我右键单击表格视图并在引用插座中看到了连接
标签: ios swift uitableview uitextfield reloaddata