0

我有一些自定义表格视图单元格,它们都有不同的 unib 和不同的类,并且想要重新排序单元格并持久保护它们重新排序的位置。

我已经在 TablevViewController 中注册了每个单元格和 UINib

    let test1Nib = UINib(nibName: "Test1", bundle: nil)
    myTableView.register(overViewNib, forCellReuseIdentifier: "Test1")

    let test2Nib = UINib(nibName: "Test2", bundle: nil)
    myTableView.register(todoNib, forCellReuseIdentifier: "Test2")

    let test3Nib = UINib(nibName: "Test3", bundle: nil)
    myTableView.register(financeNib, forCellReuseIdentifier: "Test3")

    let test4Nib = UINib(nibName: "Test4", bundle: nil)
    myTableView.register(upcomingNib, forCellReuseIdentifier: "Test4")

然后我将 UINibs 添加到我的 testArray 中:

    testArray.append(test1Nib)
    testArray.append(test2Nib)
    testArray.append(test3Nib)
    testArray.append(test4Nib)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        let cell = myTableView.dequeueReusableCell(withIdentifier: "Test1", for: indexPath)
        return cell
    } else if indexPath.row == 1 { 
        let cell = myTableView.dequeueReusableCell(withIdentifier: "Test2", for: indexPath)
        return cell
    } else if indexPath.row == 2 {
        let cell = myTableView.dequeueReusableCell(withIdentifier: "Test3", for: indexPath)
        return cell
    } else {
        let cell = myTableView.dequeueReusableCell(withIdentifier: "Test4", for: indexPath)
        return cell
    }

}

moveRowAt: 函数按预期执行

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedObject = self.testArray[sourceIndexPath.row]
    testArray.remove(at: sourceIndexPath.row)
    testArray.insert(movedObject, at: destinationIndexPath.row)
    NSLog("%@", "\(sourceIndexPath.row) -> \(destinationIndexPath.row)")
}

在这一点上,我遇到了一些问题 1. 重新排序后,单元格被重新加载,因为我已将它们的索引路径固定为静态值,现在问题是如何防止它们自行重新排序和 2. 我怎样才能坚持这一点命令

我希望我能在这里找到帮助——我现在研究了很多网络,但没有什么能满足我的需求。希望我能找到解决方案或一些链接或代码片段。多谢!

4

1 回答 1

0

您不应强制检查 indexPath 行来决定加载哪个单元格。

你应该得到他们的类型,然后切换到它。就像是:

let type = testArray[indexPath.row]
switch type {
    case Type1:
    let cell = myTableView.dequeueReusableCell(withIdentifier: "Test1", for: indexPath)
     return cell

    case Type2:
    let cell = myTableView.dequeueReusableCell(withIdentifier: "Test2", for: indexPath)
    return cell
}

如何设置此类型取决于您。有几种方法可以做到这一点,选择你最喜欢的。

于 2018-03-26T21:45:00.703 回答