我正在尝试使用alertViewController来获取文本,将其添加到我的字符串数组中,然后使用新添加的单元格重新加载tableView。重新加载后,格式似乎存在问题。
import UIKit
class TableViewController: UITableViewController, UINavigationControllerDelegate {
// store the tasks in an array of strings
var tasks = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Task List"
self.navigationItem.rightBarButtonItem = self.editButtonItem
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addRow))
}
func addRow() {
let ac = UIAlertController(title: "Add a task to the list", message: nil, preferredStyle: .alert)
// add a text field
ac.addTextField {
(textField) -> Void in
textField.placeholder = ""
}
// add "cancel" and "ok" actions
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
let createNewRow = UIAlertAction(title: "OK", style: .default) { action -> Void in
let text = ac.textFields?.first?.text
self.tasks.append(text!)
self.loadView()
}
ac.addAction(createNewRow)
present(ac, animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Task", for: indexPath)
cell.textLabel?.text = tasks[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tasks.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
答案 0 :(得分:1)
您的问题是在警报视图控制器的操作中调用self.loadView()而不是self.tableView.reloadData():
let createNewRow = UIAlertAction(title: "OK", style: .default) { action -> Void in
let text = ac.textFields?.first?.text
self.tasks.append(text!)
self.tableView.reloadData() // self.loadView() is wrong.
}
ac.addAction(createNewRow)
来自Apple的文档:https://developer.apple.com/reference/uikit/uiviewcontroller/1621454-loadview
你永远不应该直接调用这个方法。视图控制器调用 请求view属性但当前为nil时此方法。 此方法加载或创建视图并将其分配给视图 属性。