重新排序 UITableView 单元格并跟踪索引

Posted

技术标签:

【中文标题】重新排序 UITableView 单元格并跟踪索引【英文标题】:reordering UITableView cells and tracking the index 【发布时间】:2015-12-13 20:30:56 【问题描述】:

我有一个单词数组,它们以特定顺序 word1、word2、word3、word4、word5 等显示在 UITableView 中。Core data 中有一个名为 wordIndex 的每个单词的属性,它跟踪每个单词的索引因此用户可以编辑表格并更改字序。每次进行移动时,我都尝试使用 moveRowAtIndexPath 来更新表中所有单词的 wordIndex,但这种方法似乎没有使用 indexPath.row。如果有人遇到过这样做的巧妙方法,请提前致谢?

我的代码是:

  func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) 
    let wordToMove = words[sourceIndexPath.row]
    words.removeAtIndex(sourceIndexPath.row)
    words.insert(wordToMove, atIndex: destinationIndexPath.row)

    wordToMove.wordIndex = destinationIndexPath.row // seems to always have an index of 2
 // and what about updating all the other indexes above and below the moved word? 
 // indexPath.row is not allowed in this method to iterate over all the rows in the table....

    for words[(indexPath.row) == 0]; words[(indexPath.row) = words.count]; words[(indexPath.row)++]  
        word?.wordIndex = indexPath.row
    
    tableView.reloadData()
    coreDataStack.saveMainContext()

【问题讨论】:

【参考方案1】:

请改用fromIndexPath.rowtoIndexPath.row

【讨论】:

以上是关于重新排序 UITableView 单元格并跟踪索引的主要内容,如果未能解决你的问题,请参考以下文章

UITableView 重新加载除一个以外的所有单元格

重新加载 UITableView 数据而不是可见单元格

UITableView:单击单元格并使用 UIWebView 打开单元格中的链接

如何实现(几乎)全视图 uitableview 可以滚动过去最后一个单元格并在 iOS 中显示更多元素

如何制作像 UITableView 一样的动画重新排序单元格?

在 UITableView 中重新排序单元格会取消 Swift 中单元格的功能?