【问题标题】:swift - save reorder of custom static uitableviewcellswift - 保存自定义静态 uitableviewcell 的重新排序
【发布时间】:2018-03-26 18:09:30
【问题描述】:

我有一些自定义的 tableview 单元格,它们都有不同的 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. 我怎样才能坚持这个订单

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

【问题讨论】:

    标签: ios swift uitableview uinib


    【解决方案1】:

    您不应强制检查 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
    }
    

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

    【讨论】:

    • 感谢您的快速回答!按预期工作-现在我需要处理细胞的持久性-但那是另一个话题;-)非常感谢!
    • @Michael 欢迎您。请选择此答案作为正确答案并投票。谢谢!
    • @gnogames 已经投了赞成票,但由于我是 Stackoverflow 的新人,并且代表人数少于 15,因此它不会向公众展示,但它很重要 ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多