在我的手机里有一个按钮。我使用以下代码为此按钮添加了索引行和操作。
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
委托(delegate)这个过程
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]
}
最佳答案
除非您或用户编辑表格(添加/删除/重新排序单元格),否则 indexPaths 应该是正确的。听起来您正在这样做,这意味着您的方法行不通。
当您插入/删除/重新排序单元格时,返回并编辑单元格按钮上的标签会很困惑且容易出错。
最好放弃将项目行保存到按钮标记中的方法。而是获取按钮的原点,将其转换为 TableView 的坐标空间(使用 convertPoint:toView:
或 convertPoint:fromView:
)并向 TableView 询问索引该点的路径使用 UITableView
方法 indexPathForRowAtPoint
。
关于ios - 更新索引路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33945727/