【问题标题】:swift uitableview reorder cells except the last cellswift uitableview 重新排序除最后一个单元格之外的单元格
【发布时间】:2018-10-31 09:19:44
【问题描述】:

几天前,我从 Stack Overflow 那里得到了很好的建议。这是为了防止最后一个单元格在 UITableView 中移动。它使用以下代码。

func tableView (_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        if indexPath.row <myTableviewArray.count {
            return true
        }
        return false
    }

我用来移动单元格的代码是:

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        if destinationIndexPath.row != menuDic.count {
            let movedObject = menuDic[sourceIndexPath.row]
            menuDic.remove(at: sourceIndexPath.row)
            menuDic.insert(movedObject, at: destinationIndexPath.row)
        }
    }

但是出现了一个意想不到的问题。另一个牢房正在最后一个牢房的下方移动!除了最后一个单元格之外的单元格不得移动到最后一个单元格下方。最后一个单元格应该总是最后一个。

我使用了以下两个代码,但都失败了。

func tableView (_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
        if proposedDestinationIndexPath.row == myTableviewArray.count - 1 {
            return IndexPath (row: myTableviewArray.count - 1, section: 0)
        }
        return proposedDestinationIndexPath
    }

func tableView (_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        if destinationIndexPath.row! = myTableviewArray.count {
            let movedObject = myTableviewArray [sourceIndexPath.row]
            myTableviewArray.remove (at: sourceIndexPath.row)
            menuDic.insert (movedObject, at: destinationIndexPath.row)
        }
    }

使用这两个代码,单元格仍将移动到最后一个单元格的下方。堆栈溢出。谢谢你! :)

【问题讨论】:

    标签: ios swift uitableview uitableviewrowaction


    【解决方案1】:

    indexPath.row 从零开始。如果myTableviewArray 是您的数据源。

    indexPath.row &lt;myTableviewArray.count,这永远是真的。

    尝试使用:

    func tableView (_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
            if indexPath.row < myTableviewArray.count - 1 {
                return true
            }
            return false
        }
    

    【讨论】:

    • 感谢您的回复 :) 我的数据源始终是 MyArray + 1。因为我的数据源始终附加 +1(它是按钮)。我试过这个,但又失败了
    • func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { letmovedObject = menuDic[sourceIndexPath.row] menuDic.remove(at: sourceIndexPath.row) if destinationIndexPath.row == menuDic.count { menuDic.insert(movedObject, at: sourceIndexPath.row) } menuDic.insert(movedObject, at:destinationIndexPath.row) }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2021-03-21
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多