数组内容更改后,如何使表视图中的单元格使用数组作为其数据?

时间:2019-07-03 13:05:43

标签: swift uitableview

我正在快速编写一个具有两个屏幕的简短应用程序。在第一个屏幕上,用户输入数据并保存,然后在第二个屏幕上,数据显示在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

}

tasksarray,其中存储了多个内容相似的dictionaries

我的问题是,当另一个dictionary添加到array时,表视图中的cells不会改变。任何帮助将不胜感激:)

1 个答案:

答案 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
}