在表视图中滑动并删除带有两个部分的行,并将删除的名称添加到第二个部分



请帮忙,我有一个带名称的数组,当我选择一个单元格时,我会将所选的名称添加到表视图的第二部分,并从第一部分删除该名称(这里很好(,但如果我出于某种原因不想在第二部分使用该名称,我希望能够滑动该单元格,删除该名称,然后再次将其添加到表的第一部分。当我对代码执行此操作时,由于删除了一行,导致行数失败。我想不通。

这是我的密码。

import UIKit
class QuestionsVC: UIViewController {

@IBOutlet weak var namesTableView: UITableView!
var array1 = ["Jill","Clark","Rose","Peter","Louis"]
var array2 = [String]()

override func viewDidLoad() {
super.viewDidLoad()
namesTableView.dataSource = self
namesTableView.delegate = self

}
}
extension QuestionsVC: UITableViewDataSource, UITableViewDelegate {

func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return array1.count
}
return array2.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.textLabel?.text = array1[indexPath.row]
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")


cell?.textLabel?.text = array2[indexPath.row]

return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
array2.append(array1[indexPath.row])
if let index = array1.firstIndex(of: array1[indexPath.row]) {
array1.remove(at: index)
}
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0 {
return false
}else{
return true
}
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (_, indexPath) in
self.array2.remove(at: indexPath.row)
self.array1 += [self.array2[indexPath.row]]

tableView.deleteRows(at: [indexPath], with: .fade)
}
return [deleteAction]
}
}

您必须删除第1节中的行,并同时插入第0节中的列

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (_, indexPath) in
let item = self.array2.remove(at: indexPath.row)
let insertionIndex = self.array1.count
self.array1.append(item)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.insertRows(at: [IndexPath(row: insertionIndex, section: 0)], with: .automatic)
tableView.endUpdates()
}
return [deleteAction]
}
}

替换行

tableView.deleteRows(at: [indexPath], with: .fade)

带有

tableView.reloadData()

最新更新