我正在嘗試在 Swift 中創建一個待辦事項應用程式。但有一個問題。當有人按下 addTodo 按鈕時,它會將 todo 添加到 todos 陣列中。然后我重新加載 tableView。但它沒有在螢屏上顯示新的待辦事項。
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var inputBar: UITextField!
@IBOutlet weak var tableView: UITableView!
var todo : [String] = ["abc", "def", "dhe"]
func reload() {
DispatchQueue.main.async {
self.tableView.reloadData();
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell");
tableView.dataSource = self
}
@IBAction func addTodo(_ sender: UIButton) {
if var todo = inputBar.text {
print(todo);
todo.append(todo)
reload()
}
}
}
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell;
cell.task.text = todo[indexPath.row];
print("Running");
return cell;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todo.count;
}
}
uj5u.com熱心網友回復:
這是一個非常有趣的錯誤。
在addTodo您將區域變數的值附加todo到自身而不是具有相同名稱的陣列(實際上是self.todo.
名稱陣列總是以復數形式——或者至少使用不同的名稱——以避免這種混淆
var todos : [String] = ["abc", "def", "dhe"]
但是,由于is never的text屬性,您可以簡單地寫UITextFieldnil
@IBAction func addTodo(_ sender: UIButton) {
todos.append(inputBar.text!)
reload()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429153.html
上一篇:CoreData物體模型
