我知道如果他们在一个部分下面交换单元格,因为互联网充满了这个,但我正在努力与两个部分相同。我不能移动每个单元格,因为显然索引超出了范围。我认为没有必要发布整个代码所以我只会粘贴重要的位
我已声明:
let sections: [String] = ["Box", "Inventory"]
var s1Data: [UIImage] = [] //
var s2Data: [UIImage] = [] //these are filled by other function
let sectionsImages: [UIImage] = [#imageLiteral(resourceName: "blackBox"), #imageLiteral(resourceName: "blackBag")]
var sectionData: [[UIImage]] = []
在viewDidLoad()中:
tableView.isEditing = true
tableView.delegate = self
tableView.dataSource = self
sectionData = [s1Data, s2Data]
然后有很多tableView函数,但是我无法通过的那个和我正在谈论的那个:
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
{
let item = sectionData[sourceIndexPath.row]
sectionData.remove(at: sourceIndexPath.row)
sectionData.insert(item, at: destinationIndexPath.row)
}
所以,交换正常,直到我尝试交换最后一个图像单元,因为提到'越界'失败。我知道我应该将项目声明为:
let item = sectionData[sourceIndexPath.section][sourceIndexPath.row]
但是“删除”和“插入”呢? 我很感谢你的帮助
编辑:
我做到了,虽然我不知道它是否是更简单的方法之一。无论如何:
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
{
if sourceIndexPath.section == 0 && destinationIndexPath.section == 0
{
let item = sectionData[0][sourceIndexPath.row]
sectionData[0].remove(at: sourceIndexPath.row)
sectionData[0].insert(item, at: destinationIndexPath.row)
}
else if sourceIndexPath.section == 0 && destinationIndexPath.section == 1
{
let item = sectionData[0][sourceIndexPath.row]
sectionData[0].remove(at: sourceIndexPath.row)
sectionData[1].insert(item, at: destinationIndexPath.row)
}
else if sourceIndexPath.section == 1 && destinationIndexPath.section == 0
{
let item = sectionData[1][sourceIndexPath.row]
sectionData[1].remove(at: sourceIndexPath.row)
sectionData[0].insert(item, at: destinationIndexPath.row)
}
else if sourceIndexPath.section == 1 && destinationIndexPath.section == 1
{
let item = sectionData[1][sourceIndexPath.row]
sectionData[1].remove(at: sourceIndexPath.row)
sectionData[1].insert(item, at: destinationIndexPath.row)
}
else
{
print("ERROR - SWAP MALFUNCTION")
}
}
答案 0 :(得分:0)
这就是我的方法,插入使用destinationIndexPath.section:
groupItems[sourceIndexPath.section].remove(at: sourceIndexPath.row)
groupItems[destinationIndexPath.section].insert(movedObject, at: destinationIndexPath.row)