更新索引路径

时间:2015-11-26 19:21:32

标签: ios swift uitableview

在我的手机中,我有一个按钮。我使用以下代码为此按钮添加了索引行和操作。

func showAllAction(sender:AnyObject) {
        self.performSegueWithIdentifier("showProduct", sender: sender)
    }

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:
        indexPath) as! CartTableViewCell

        cell.showAllButton.tag = indexPath.row
        cell.showAllButton.addTarget(self, action: "showAllAction:", forControlEvents: .TouchUpInside)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "showProduct" {
            let destinationController = segue.destinationViewController as! ProductController
            destinationController.shopItem = self.Items[sender.tag]
        }
    }

当用户点击按钮时,他会转到另一个页面。但是当我向表添加新单元格时,我的索引是错误的。每次添加删除等时,如何重新计算行路径。?

现在我使用NSFetchedResultsControllerDelegate

委托此流程
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

        switch type {
            case .Insert:
                if let _newIndexPath = newIndexPath {
                    tableView.insertRowsAtIndexPaths([_newIndexPath], withRowAnimation: .Fade)
                }
            case .Delete:
                if let _indexPath = indexPath {
                    tableView.deleteRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade)
                }
            case .Update:
                if let _indexPath = indexPath {
                    tableView.reloadRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade)
                }
            default:
                    self.tableView.reloadData()
        }

        self.items = controller.fetchedObjects as! [Item]
    }

1 个答案:

答案 0 :(得分:1)

indexPaths应该是正确的,除非你或用户编辑表格(添加/删除/重新排序单元格。)听起来你正在这样做,这意味着你的方法不起作用。

当您插入/删除/重新排序单元格时,返回并编辑单元格按钮上的标记会很麻烦且容易出错。

最好放弃将项目行保存到按钮标记中的方法。而是获取按钮的原点,将其转换为表视图的坐标空间(使用convertPoint:toView:convertPoint:fromView:)并使用UITableView方法向表视图询问该点的索引路径indexPathForRowAtPoint