我正在快速编写一个具有两个屏幕的简短应用程序。在第一个屏幕上,用户输入数据并保存,然后在第二个屏幕上,数据显示在tableView
。但是我似乎无法tableView
适应变化array
。
我环顾四周,似乎无法找到解决方案,但是我对此并不陌生,所以我可能在错误的地方寻找。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! BunchOfCells
cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0)
tableview.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0)
if tasks.count != 0 {cell.label.text = tasks[indexPath.item]["Title"]}
return cell
}
func createTask(){
let decider = UserDefaults.standard.object(forKey: "buttonPressed") as? Bool
if (decider == true){
let nameOfTask = UserDefaults.standard.object(forKey: "taskName") as! String
let importanceOfTask = UserDefaults.standard.object(forKey: "importance") as! String
let dateOfTask = UserDefaults.standard.object(forKey: "taskDate") as! String
let desOfTask = UserDefaults.standard.object(forKey: "taskDescription") as! String
taskInfo["Title"] = nameOfTask
taskInfo["Importance"] = importanceOfTask
taskInfo["Date"] = dateOfTask
taskInfo["Description"] = desOfTask
tasks.append(taskInfo)
print(tasks)
}
var tasks: [[String:String]] = [] as Array
var taskInfo: [String:String] = ["Title":"", "Importance":"", "Date":"", "Description":""]
let tableview: UITableView = {
let tv = UITableView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.separatorColor = UIColor.white
return tv
}()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let NumOfCell = tasks.count
return NumOfCell
}
tasks
是array
存储dictionaries
具有相似内容的倍数。
我的问题是,当另一个dictionary
被添加到array
该cells
表中的观点并没有改变。任何帮助,将不胜感激 :)
呼叫reloadData()
在tableView
您创建了一个新的任务后,即
func createTask(){
let decider = UserDefaults.standard.bool(forKey: "buttonPressed")
if decider {
//your rest of the code...
}
tableView.reloadData()
}
不要忘了创建一个outlet
为tableView
你的viewController
。
@IBOutlet weak var tableView: UITableView!
当然,正如@vadian所建议的,tableView(_:cellForRowAt:)
实现必须像
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! BunchOfCells
cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0)
cell.label.text = tasks[indexPath.item]["Title"]
return cell
}
实际上必须有出口。请注意the中的拼写
cellForRow
。@vadian没得到你。我在代码中有任何错误吗?
不,您没有,但是很明显
tableview
该类中有一个出口(带有小写字母v)。@vadian哦,好的。了解。谢谢你的收获。我在答案中对此进行了更新。实际上,我在方法本身中使用了tableView参数。
强烈建议在数据源和委托方法中始终使用给定的
tableView
参数。