我正在快速编写一个具有两个屏幕的简短应用程序。在第一个屏幕上,用户输入数据并保存,然后在第二个屏幕上,数据显示在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
不会改变。任何帮助将不胜感激:)
答案 0 :(得分:0)
在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
}