用于UITableView的NSFetchedResultsController在插入更改时滚动到顶部

时间:2015-04-26 16:59:09

标签: ios objective-c uitableview

我有一个由NSFetchedResultsController备份的UITableView。我希望滚动到tableView的顶部,在插入表中的行之后隐藏搜索栏,即

-> row created
-> row inserted
-> row insert animation finished
-> **scroll to top hiding search controller**

知道某行是否已被添加的唯一方法是查看NSFetchedResultsControllerDelegate API controller:didChangeObject:atIndexPath:forChangeType:newIndexPath

1 个答案:

答案 0 :(得分:2)

我使用CATransactionUITableView完成动画时收到通知:

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [CATransaction begin];
    [CATransaction setCompletionBlock:^{
        if(self.shouldScrollToTop) {
            [self.tableView setContentOffset:CGPointZero animated:YES];
        }
        self.shouldScrollToTop = NO;
    }];

    [self.tableView beginUpdates];
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];

    [CATransaction commit];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:@[ newIndexPath ] withRowAnimation:UITableViewRowAnimationAutomatic];

            self.shouldScrollToTop = YES;
            break;
    }
}