【问题标题】:Inserting new row in tableview duplicates last row在 tableview 中插入新行会重复最后一行
【发布时间】:2020-07-11 09:08:29
【问题描述】:

当我使用tableView.insertRows 插入新行时,由于某种原因,有时它会插入一个与最后一行重复的新行,而有时它会通过插入新添加的行来按预期工作。我真的很困惑......我做错了什么?

var list: Results<Item>?
var selectedCategory: Category = Category()

selectedCategory 值将在可渗透视图控制器中设置

override func viewDidLoad() {
    super.viewDidLoad()
    list = selectedCategory.items.sorted(byKeyPath: "title")
}
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
        if let item = list?[indexPath.row] {
            cell.textLabel?.text = item.title
            cell.accessoryType = item.done ? .checkmark : .none
        }
        return cell
    }
    @IBAction func addNewItem(_ sender: UIBarButtonItem) {
        let newItem = Item()
        var textField = UITextField()
        
        let alert = UIAlertController(title: "Add New To Do", message: nil, preferredStyle: .alert)
        alert.addTextField { item in
            textField = item
        }
        let action = UIAlertAction(title: "Add", style: .default) { action in
            newItem.title = textField.text!
            try! self.realm.write {
                self.selectedCategory.items.append(newItem)
                self.realm.add(newItem)
            }
            let pos = self.list!.count-1
            self.tableView.insertRows(at: [IndexPath.init(row: pos , section: 0)], with: .left)
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }

【问题讨论】:

    标签: ios swift xcode uitableview


    【解决方案1】:

    在cell类中,添加prepareForReuse()方法,清除cell内容。应该有帮助。

    Apple Doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 2012-01-03
      • 2011-11-26
      相关资源
      最近更新 更多