【发布时间】: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