gpt4 book ai didi

iOS - 核心数据 - 表格 View 滚动到新添加的记录

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:19:52 25 4
gpt4 key购买 nike

概述:

我有一个包含以下内容的 iOS 项目:

  • 核心数据(使用NSFetchedResultsController)
  • 在 TableView 中显示数据 (UITableView)

我想做什么:

  • 当用户添加记录时,我想滚动到新添加的记录。

我做了什么

  1. 添加新记录时,在 NSFetchedResultsControllerDelegate 方法中,当类型为插入/更新/移动时,我将索引路径存储在属性 lastAddedIndexPath
  2. 调用保存后,我滚动到“lastAddedIndexPath”

代码(NSFetchedResultsControllerDelegate)

- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"going to store insert - scroll");
self.lastAddedIndexPath = newIndexPath;
break;

case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;

case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"going to store update - scroll");
self.lastAddedIndexPath = newIndexPath;
break;

case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
NSLog(@"going to store move - scroll");
self.lastAddedIndexPath = newIndexPath;
break;
}
}
}

滚动代码

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if (self.beganUpdates) //already [self.tableView beginUpdates] invoked
{
[self scrollToLastAddedIndexPath]; //contains the logic to scroll
[self.tableView endUpdates];
}
}

问题

  • 我认为记录是在不同的线程中异步添加到 TableView 中的。
  • 所以即使在保存数据库之后,当我滚动到 lastAddedIndexPath 时,表中的记录还不存在。

问题

  1. 将记录添加到 TableView 后,如何滚动到新添加的记录路径?
  2. 我应该使用通知来了解数据库何时保存吗?
  3. 还有其他替代方法吗?

最佳答案

您的滚动必须发生在 [self.tableView endUpdates] 之后,因为新行直到那时才添加到表格中。所以交换两个语句:

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
{
if (self.beganUpdates) //already [self.tableView beginUpdates] invoked
{
[self.tableView endUpdates];
[self scrollToLastAddedIndexPath]; //contains the logic to scroll

}
}

关于iOS - 核心数据 - 表格 View 滚动到新添加的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10203341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com