温馨提示:本文翻译自stackoverflow.com,查看原文请点击:swift - How do I make cells in a table view use array for their data after the content of array has changed?
swift uitableview

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

发布于 2020-03-27 10:17:17

我正在快速编写一个具有两个屏幕的简短应用程序。在第一个屏幕上,用户输入数据并保存,然后在第二个屏幕上,数据显示在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被添加到arraycells表中的观点并没有改变。任何帮助,将不胜感激 :)

查看更多

查看更多

提问者
Hubert Rzeminski
被浏览
182
PGDev 2019-07-03 21:19

呼叫reloadData()tableView您创建了一个新的任务后,即

func createTask(){
    let decider = UserDefaults.standard.bool(forKey: "buttonPressed")
    if decider {
        //your rest of the code...
    }
    tableView.reloadData()
}

不要忘了创建一个outlettableView你的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
}