【问题标题】:tableView.reloadData() adds a UIView that it should not dotableView.reloadData() 添加了一个不应该做的 UIView
【发布时间】:2019-05-29 16:32:03
【问题描述】:

我有一个带有可选属性的模式。正如您可能已经猜到的那样,我只为非可选属性添加了一个 UIView。在以下代码中,dueDate 是可选的。第一个有截止日期,第二个没有。

let london = Task( name: "Hello from London",
                     createdDate: Date(),
                     isCompleted: false,
                     dueDate: Date())

let madrid = Task( name: "hola desde madrid",
                     createdDate: Date(),
                     isCompleted: false)

插入单元格的数据源方法。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell

    if  let _ = tasks[indexPath.row].dueDate {
        cell.textLabel?.text = "Due Date"
    }

    return cell
}

当我打开应用程序时,它会按预期运行。只有第一个单元格有Due Date。我希望如此,因为它只是第一个有截止日期的任务。但是,当我删除第一个单元格(参见下面的代码)并重新加载日期时,Due Date 也会添加到第二个单元格中。我不明白。我希望它不应该被添加,因为第二个任务没有截止日期

删除单元格的委托方法

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let remove = UITableViewRowAction(style: .normal, title: "Remove") { action, index in
        let task =  self.tasks.remove(at: indexPath.row)
        print(task.name) //
        tableView.reloadData()
    }
    remove.backgroundColor = .red

    return [remove]
}

我做错了什么?我该如何解决这个问题?


如果您需要更多信息,请尽管询问。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    是因为出队,所以换成

    cell.textLabel?.text = tasks[indexPath.row].dueDate != nil ? "London" : ""
    

    当您删除第一个单元格时,它会被第二个单元格出列,因此您会看到第二个单元格配置了已删除单元格的属性,因此在cellForRowAt 中,您需要确保每次运行都设置代码

    【讨论】:

    • 谢谢。有用。如果dueDate 为nil,如何在TableViewCell 中添加UIView?
    • 将它添加到原型单元格中并使其隐藏,当日期为零时显示它
    【解决方案2】:

    看看你的 cellForRow:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
    
        if let _ = tasks[indexPath.row].dueDate {
            cell.textLabel?.text = "London"
        }
    
        return cell
    }
    

    现在,当您删除一个单元格时,您调用 reloadData 对以前有截止日期但现在没有截止日期的单元格。由于if 没有被执行,你没有对单元格做任何事情。添加else 案例。

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
    
        if let _ = tasks[indexPath.row].dueDate {
            cell.textLabel?.text = "London"
        }
        else {
            cell.textLabel?.text = nil
        }
    
        return cell
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 2012-01-25
      • 1970-01-01
      相关资源
      最近更新 更多